├── .gitignore
├── README.md
├── app
├── .gitignore
├── build.gradle
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── it
│ │ └── uncle
│ │ └── androidassert
│ │ └── ExampleInstrumentedTest.kt
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── it
│ │ │ └── uncle
│ │ │ └── androidassert
│ │ │ ├── AssertCase.java
│ │ │ ├── MainActivity.java
│ │ │ ├── MyApp.java
│ │ │ └── TestActivity.java
│ └── res
│ │ ├── drawable-v24
│ │ └── ic_launcher_foreground.xml
│ │ ├── drawable
│ │ └── ic_launcher_background.xml
│ │ ├── layout
│ │ ├── activity_main.xml
│ │ └── activity_test.xml
│ │ ├── mipmap-anydpi-v26
│ │ ├── ic_launcher.xml
│ │ └── ic_launcher_round.xml
│ │ ├── mipmap-hdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-mdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ ├── mipmap-xxxhdpi
│ │ ├── ic_launcher.png
│ │ └── ic_launcher_round.png
│ │ └── values
│ │ ├── colors.xml
│ │ ├── strings.xml
│ │ └── styles.xml
│ └── test
│ └── java
│ └── com
│ └── it
│ └── uncle
│ └── androidassert
│ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
└── wrapper
│ ├── gradle-wrapper.jar
│ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
├── img
├── assumenosideeffects.png
├── debug-release.png
└── no-assumenosideeffects.png
├── lib-android-assert
├── .gitignore
├── build.gradle
├── consumer-rules.pro
├── proguard-rules.pro
└── src
│ ├── androidTest
│ └── java
│ │ └── com
│ │ └── it
│ │ └── uncle
│ │ └── lib
│ │ └── androidassert
│ │ └── ExampleInstrumentedTest.java
│ ├── main
│ ├── AndroidManifest.xml
│ ├── java
│ │ └── com
│ │ │ └── it
│ │ │ └── uncle
│ │ │ └── lib
│ │ │ └── util
│ │ │ ├── AndroidAssert.java
│ │ │ └── ThreadTypeUtil.java
│ └── res
│ │ └── values
│ │ └── strings.xml
│ └── test
│ └── java
│ └── com
│ └── it
│ └── uncle
│ └── lib
│ └── androidassert
│ └── ExampleUnitTest.java
└── settings.gradle
/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | /.idea/
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 | [  ](https://bintray.com/vectorzeng/maven/android-assert/0.0.2/link)
4 |
5 | - [x] 一、简介
6 | - [x] 二、什么是断言,什么情况下应该使用androidAssert?
7 | - [x] 三、在release版本中移除断言代码,只在debug中保留
8 | - [x] 四、集成AndroidAssert库
9 | - [x] 五、API
10 |
11 |
12 |
13 | [blog](https://juejin.im/post/5ed670e56fb9a047a96a7c9f)
14 |
15 | [readme中的截图不显示的话,点这里](https://juejin.im/post/5ed670e56fb9a047a96a7c9f)
16 |
17 |
18 |
19 | ## 一、简介
20 |
21 | > android-assert是一个非常简单轻量的android断言库。类似于junit的Assert类。
22 | >
23 | > android-assert不是用来写测试用例的,可以直接在项目代码中使用他。
24 | >
25 | > 在debug模式下,断言失败将会抛出断言异常 AssertionFailedError,在release模式下,将不会抛出异常。
26 |
27 |
28 |
29 | ## 二、什么是断言,什么情况下应该使用androidAssert?
30 |
31 | 通常断言(assert)是用在单元测试,用来校验函数返回的结果。用在自动化测试用来校验程序运行结果。
32 |
33 | 但是我们接下来要讨论的并不是单元测试中使用断言,而是在项目业务代码中使用断言。
34 |
35 | 我们一起来看几个,大家非常熟悉的例子。这些情况下使用断言会让代码更加优雅,更加健壮。
36 |
37 |
38 |
39 | ### 例子1,writeFile
40 |
41 | ```java
42 | /**
43 | * 我们希望只在子线程中调用writeFile(),主线程中调用可能会导致ui卡顿或者anr。
44 | *
45 | * 如果在主线程调用writeFile(),我们打印日志警告开发者
46 | */
47 | public void writeFile() {
48 | //主线程,打印日志警告开发者
49 | if(!ThreadTypeUtil.isSubThread()){
50 | Log.e(TG, "you should call writeFile at sub thread");
51 | }
52 | // write file ...
53 | }
54 | ```
55 |
56 | 当出现有开发人员,尝试在主线程中调用writeFile()方法时,我们通过 **日志警告** ,开发者。但是,日志提示很弱,往往会被开发者忽略掉。
57 |
58 | **于是我们改良了下代码:**
59 |
60 | ```java
61 | public void writeFile() {
62 | //debug版本,主线程中调用 writeFile ,直接抛出异常中断程序运行
63 | if(!ThreadTypeUtil.isSubThread()){
64 | if(BuildConfig.DEBUG) {
65 | throw new RuntimeException("you should call writeFile at sub thread");
66 | }
67 | }
68 | // write file ...
69 | }
70 | ```
71 |
72 | 当程序员企图在主线程中调用writeFile(),在debug模式下,我们直接抛出异常,让程序崩溃。以中断他的开发。强制他优化代码。
73 |
74 | 我们引入断言库,**继续改造代码,让代码更简洁漂亮:**
75 |
76 | ```java
77 | /**
78 | * 在debug模式,下将直接抛出异常 AssertionFailedError。让开发者
79 | * 在release模式,不会抛出异常,会正常执行writeFile()函数。
80 | */
81 | public void writeFile() {
82 | AndroidAssert.assertSubThread();
83 | // write file ...
84 | Log.i(TG, "writeFile...");
85 | }
86 | ```
87 |
88 | AndroidAssert.assertSubThread()断言为子线程的意思是,**断定当前线程一定是子线程,如果不是,那么抛出异常 AssertionFailedError**。
89 |
90 |
91 |
92 | **继续优化**
93 |
94 | > 只有在debug版本,AndroidAssert 类,才有用;
95 | >
96 | > 在release版本的apk上,**能否把 AndroidAssert 相关调用的代码删除?**
97 | >
98 | > 我们先挖个坑,把例子讲完,再将release删除代码的方法。大家先忍一忍。
99 |
100 |
101 |
102 |
103 |
104 | ### 例子2,updateUI
105 |
106 | ```java
107 | /**
108 | * 在release版本,如果在子线程中调用updateUI,我们直接return,不做ui更新操作。
109 | * 但是在debug版本,如果在子线程中调用updateUI,直接出异常,让开发者发现异常调用并解决。
110 | */
111 | public void updateUI() {
112 | boolean isMainThread = ThreadTypeUtil.isMainThread();
113 | if (!isMainThread) {
114 | AndroidAssert.fail("updateUI must be called at main thread");
115 | return;
116 | }
117 | //update ui ....
118 | Log.i(TG, "updateUI...");
119 | }
120 | ```
121 |
122 |
123 |
124 | ### 例子3,startMainActivity
125 |
126 | ```java
127 | /**
128 | * 断言context为非空,如果为null,debug模式下抛出异常 AssertionFailedError
129 | */
130 | public void startMainActivity(Context context) {
131 | AndroidAssert.assertNotNull("context must not null", context);
132 | if (context == null) {
133 | return;
134 | }
135 | //startMainActivity...
136 | Log.i(TG, "startMainActivity...");
137 | }
138 | ```
139 |
140 |
141 |
142 | ## 三、我们继续改良,例子1,在release版本中移除断言代码,只在debug中保留
143 |
144 | > 只有在debug版本,AndroidAssert 类,才有用;
145 | >
146 | > 在release版本的apk上,**能否把 AndroidAssert 相关调用的代码删除?**
147 | >
148 | > 或者说打包的时候,把 AndroidAssert 相关的调用的代码 和 AndroidAssert类的代码 全部删除,再打包。
149 |
150 | 于是我想到了proguard。
151 |
152 | 在proguard中添加如下配置即可:
153 |
154 | ```pro
155 | # -dontoptimize ## 注意注意注意,proguard中配置dontoptimize;将会导致proguard不做代码优化,不会删除AndroidAssert类
156 | -assumenosideeffects class com.it.uncle.lib.util.AndroidAssert{
157 | public *;
158 | }
159 | ```
160 |
161 | 注意,注意,千万注意:**不能开-dontoptimize,开了,-assumenosideeffects将失效**
162 |
163 |
164 |
165 | 对assumenosideeffects用法有疑惑的可以,看下这篇blog:https://blog.csdn.net/jiese1990/article/details/21752159
166 |
167 | 以及官方wiki:https://www.guardsquare.com/en/products/proguard/manual/usage#assumenosideeffects
168 |
169 |
170 |
171 | **校验assumenosideeffects是否生效**
172 |
173 | 1. 配置成功后,打包在mapping中搜索:com.it.uncle.lib.util.AndroidAssert
174 |
175 | proguard未配置 -assumenosideeffects 的mapping.txt文件
176 |
177 | 
178 |
179 |
180 |
181 | proguard配置了 -assumenosideeffects 的mapping.txt文件:
182 |
183 | 
184 |
185 |
186 |
187 |
188 |
189 | 2. 反编译debug和release包对比。
190 |
191 | 比如,我们demo里的[TestActivity](app/src/main/java/com/it/uncle/androidassert/TestActivity.java)
192 |
193 | ```java
194 | public class TestActivity extends MainActivity {
195 |
196 | @Override
197 | protected void onCreate(@Nullable Bundle savedInstanceState) {
198 | super.onCreate(savedInstanceState);
199 | setContentView(R.layout.activity_test);
200 |
201 | AndroidAssert.assertNotNull(getIntent());
202 | }
203 | }
204 | ```
205 |
206 | 我们分别反编译debug和release包,找到TestActivity类的代码对比:
207 |
208 | 
209 |
210 |
211 |
212 |
213 |
214 | ## 四、集成AndroidAssert库
215 |
216 | - gradle引入
217 |
218 | ```gradle
219 | implementation 'com.ituncle:android-assert:0.0.2'
220 | ```
221 |
222 | - 初始化sdk,尽早调用,建议在Application#onCreate的时候调用。
223 |
224 | ```java
225 | //初始化----断言失败时,是否抛出异常
226 | AndroidAssert.enableThrowError(BuildConfig.DEBUG);//我们设置为debug模式下,断言失败才抛出异常
227 | ```
228 |
229 | - 添加proguard,在开启混淆的版本中,移除AndroidAssert的代码
230 |
231 | ```pro
232 | # -dontoptimize ## 注意注意注意,proguard中配置dontoptimize;将会导致proguard不做代码优化,不会删除AndroidAssert类
233 | -assumenosideeffects class com.it.uncle.lib.util.AndroidAssert{
234 | public *;
235 | }
236 | ```
237 |
238 |
239 |
240 | ## 无、API
241 |
242 | ```java
243 | public class AndroidAssert {
244 |
245 | /**
246 | * 尽早调用,建议在Application#onCreate的时候调用。
247 | *
248 | * @param enable 当断言失败时,是否抛出异常 AssertionFailedError
249 | */
250 | public static void enableThrowError(boolean enable){}
251 |
252 | /**
253 | * 断言失败,抛出断言异常
254 | */
255 | public static void fail(){}
256 | public static void fail(String message){}
257 |
258 |
259 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ thread ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
260 |
261 | /**
262 | * 检查当前是否是子线程,如果不是,抛出断言异常
263 | */
264 | public static void assertSubThread() {}
265 |
266 | /**
267 | * 检查当前是否是主线程,如果不是,抛出断言异常
268 | */
269 | public static void assertMainThread() {}
270 |
271 |
272 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ null or nunNull ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
273 |
274 | /**
275 | * 检查object是否为为非空,如果为空,抛出断言异常
276 | */
277 | public static void assertNotNull(Object object) {}
278 | public static void assertNotNull(String message, Object object) {}
279 |
280 | /**
281 | * 检查object是否为null,如果不是null,抛出断言异常
282 | */
283 | public static void assertNull(Object object) {}
284 | public static void assertNull(String message, Object object) {}
285 |
286 |
287 |
288 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ true or false ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
289 |
290 | /**
291 | * @param condition 不是true,将抛出断言异常
292 | */
293 | public static void assertTrue(boolean condition) {
294 | assertTrue(null, condition);
295 | }
296 | public static void assertTrue(String message, boolean condition) {}
297 |
298 | /**
299 | * @param condition 不是false,将抛出断言异常
300 | */
301 | public static void assertFalse(boolean condition) {}
302 | public static void assertFalse(String message, boolean condition) {}
303 |
304 |
305 |
306 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ same ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
307 | /**
308 | * expected == actual为false,抛出断言异常
309 | */
310 | public static void assertSame(Object expected, Object actual) {}
311 | public static void assertSame(String message, Object expected, Object actual) {}
312 |
313 | /**
314 | * object != actual为false,抛出断言异常
315 | */
316 | public static void assertNotSame(Object expected, Object actual) {}
317 | public static void assertNotSame(String message, Object expected,
318 | Object actual) {}
319 |
320 |
321 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ equals ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
322 |
323 | /**
324 | * 检查expected、actual两个对象equals是否为true,如果为false那么抛出断言异常
325 | */
326 | public static void assertEquals(Object expected, Object actual) {}
327 | public static void assertEquals(String message, Object expected,
328 | Object actual) {}
329 | public static void assertEquals(boolean expected, boolean actual) {}
330 | public static void assertEquals(byte expected, byte actual) {}
331 | public static void assertEquals(char expected, char actual) {}
332 | public static void assertEquals(int expected, int actual) {}
333 | // ...
334 | }
335 | ```
336 |
337 |
--------------------------------------------------------------------------------
/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/app/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.application'
2 |
3 | apply plugin: 'kotlin-android'
4 |
5 | apply plugin: 'kotlin-android-extensions'
6 |
7 | android {
8 | compileSdkVersion 28
9 | defaultConfig {
10 | applicationId "com.it.uncle.androidassert"
11 | minSdkVersion 19
12 | targetSdkVersion 28
13 | versionCode 1
14 | versionName "1.0"
15 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
16 | }
17 | buildTypes {
18 | release {
19 | minifyEnabled true
20 | signingConfig signingConfigs.debug
21 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
22 | }
23 | }
24 | compileOptions {
25 | sourceCompatibility = 1.8
26 | targetCompatibility = 1.8
27 | }
28 | }
29 |
30 | dependencies {
31 | implementation fileTree(dir: 'libs', include: ['*.jar'])
32 | implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
33 | implementation 'androidx.appcompat:appcompat:1.0.2'
34 | implementation 'androidx.core:core-ktx:1.0.2'
35 | implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
36 | implementation project(path: ':lib-android-assert')
37 | // implementation 'com.ituncle:android-assert:0.0.1'
38 |
39 |
40 | testImplementation 'junit:junit:4.12'
41 | androidTestImplementation 'androidx.test:runner:1.1.1'
42 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
43 |
44 | }
45 |
--------------------------------------------------------------------------------
/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
23 | # -dontoptimize ## 注意注意注意,不要加添加这个配置;将会关闭优化,导致日志语句不会被优化掉。
24 | -assumenosideeffects class com.it.uncle.lib.util.AndroidAssert{
25 | public *;
26 | }
--------------------------------------------------------------------------------
/app/src/androidTest/java/com/it/uncle/androidassert/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.it.uncle.androidassert", appContext.packageName)
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
--------------------------------------------------------------------------------
/app/src/main/java/com/it/uncle/androidassert/AssertCase.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert;
2 |
3 | import android.content.Context;
4 | import android.content.Intent;
5 | import android.util.Log;
6 |
7 | import com.it.uncle.lib.util.AndroidAssert;
8 | import com.it.uncle.lib.util.ThreadTypeUtil;
9 |
10 | public class AssertCase {
11 | private static final String TG = "vz-AssertCase";
12 |
13 |
14 | // /**
15 | // * 我们希望只在子线程中调用writeFile(),主线程中调用可能会导致ui卡顿或者anr。
16 | // *
17 | // * 如果在主线程调用writeFile(),我们打印日志警告开发者
18 | // */
19 | // public void writeFile() {
20 | // //主线程,打印日志警告开发者
21 | // if(!ThreadTypeUtil.isSubThread()){
22 | // Log.e(TG, "you should call writeFile at sub thread");
23 | // }
24 | // // write file ...
25 | // Log.i(TG, "writeFile...");
26 | // }
27 |
28 | // /**
29 | // * 我们希望只在子线程中调用writeFile(),主线程中调用可能会导致ui卡顿或者anr。
30 | // *
31 | // * 如果在主线程调用writeFile(),debug模式下,我们抛出异常
32 | // */
33 | // public void writeFile() {
34 | // //debug版本,主线程中调用 writeFile ,直接抛出异常中断程序运行
35 | // if(!ThreadTypeUtil.isSubThread()){
36 | // if(BuildConfig.DEBUG) {
37 | // throw new RuntimeException("you should call writeFile at sub thread");
38 | // }
39 | //
40 | // }
41 | // // write file ...
42 | // Log.i(TG, "writeFile...");
43 | // }
44 |
45 | /**
46 | * 我们希望只在子线程中writeFile(),如果在主线程中调用会导致ui卡顿或者anr。
47 | *
48 | * 如果在主线程调用writeFile();
49 | * 在debug模式,下将直接抛出异常 AssertionFailedError。让开发者
50 | * 在release模式,不会抛出异常,会正常执行writeFile()函数。
51 | */
52 | public void writeFile() {
53 | AndroidAssert.assertSubThread();
54 | // write file ...
55 | Log.i(TG, "writeFile...");
56 | }
57 |
58 |
59 | /**
60 | * 更新UI操作必须在主线程中执行,否则将会引发crash或者界面异常。
61 | *
62 | * 在release版本,如果在子线程中调用updateUI,我们直接return,不做ui更新操作。
63 | * 但是在debug模式,如果在子线程中调用updateUI,直接出异常,让开发者发现异常调用并解决。
64 | */
65 | public void updateUI() {
66 | boolean isMainThread = ThreadTypeUtil.isMainThread();
67 | if (!isMainThread) {
68 | AndroidAssert.fail("updateUI must be called at main thread");
69 | return;
70 | }
71 | //update ui ....
72 | Log.i(TG, "updateUI...");
73 | }
74 |
75 | /**
76 | * 断言context为非空,如果为null,debug模式下抛出异常 AssertionFailedError
77 | */
78 | public void startTestActivity(Context context) {
79 | AndroidAssert.assertNotNull("context must not null", context);
80 | if (context == null) {
81 | return;
82 | }
83 | context.startActivity(new Intent(context, TestActivity.class));
84 | Log.i(TG, "startTestActivity...");
85 | }
86 |
87 |
88 | }
89 |
--------------------------------------------------------------------------------
/app/src/main/java/com/it/uncle/androidassert/MainActivity.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert;
2 |
3 | import android.app.Activity;
4 | import android.os.Bundle;
5 | import android.util.Log;
6 |
7 | import androidx.annotation.Nullable;
8 |
9 | import com.it.uncle.lib.util.AndroidAssert;
10 |
11 | public class MainActivity extends Activity {
12 | private static final String TG = "vz-MainActivity";
13 |
14 | @Override
15 | protected void onCreate(@Nullable Bundle savedInstanceState) {
16 | super.onCreate(savedInstanceState);
17 | //初始化----断言失败时,是否抛出异常,默认不抛出异常
18 | AndroidAssert.enableThrowError(BuildConfig.DEBUG);//我们设置为debug模式下,断言失败才抛出异常
19 |
20 | setContentView(R.layout.activity_main);
21 |
22 | findViewById(R.id.btn_updateUIAtMainThread).setOnClickListener(v -> {
23 | Log.e(TG, "btn_assertMainThread");
24 | new AssertCase().updateUI();//正常执行
25 | });
26 |
27 | findViewById(R.id.btn_updateUIAtSubThread).setOnClickListener(v -> {
28 | Log.e(TG, "btn_assertSubThread");
29 | new Thread(){
30 | @Override
31 | public void run() {
32 | //在debug模式下,会抛出异常AssertionFailedError
33 | new AssertCase().updateUI();
34 | }
35 | }.start();
36 |
37 | });
38 |
39 | findViewById(R.id.btn_writeFileAtMainThread).setOnClickListener(v -> {
40 | //在debug模式下,会抛出异常AssertionFailedError
41 | new AssertCase().writeFile();
42 | });
43 |
44 | findViewById(R.id.btn_startTestActivity).setOnClickListener(v -> {
45 | new AssertCase().startTestActivity(v.getContext());
46 | });
47 |
48 |
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/app/src/main/java/com/it/uncle/androidassert/MyApp.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert;
2 |
3 | import android.app.Application;
4 |
5 | import com.it.uncle.lib.util.AndroidAssert;
6 |
7 | public class MyApp extends Application {
8 |
9 | @Override
10 | public void onCreate() {
11 | super.onCreate();
12 | //初始化----断言失败时,是否抛出异常,默认不抛出异常
13 | // AndroidAssert.enableThrowError(BuildConfig.DEBUG);//我们设置为debug模式下,断言失败才抛出异常
14 | AndroidAssert.enableThrowError(true);
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/app/src/main/java/com/it/uncle/androidassert/TestActivity.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert;
2 |
3 | import android.os.Bundle;
4 |
5 | import androidx.annotation.Nullable;
6 |
7 | import com.it.uncle.lib.util.AndroidAssert;
8 |
9 | public class TestActivity extends MainActivity {
10 |
11 | @Override
12 | protected void onCreate(@Nullable Bundle savedInstanceState) {
13 | super.onCreate(savedInstanceState);
14 | setContentView(R.layout.activity_test);
15 |
16 | AndroidAssert.assertNotNull(getIntent());
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
12 |
13 |
19 |
22 |
25 |
26 |
27 |
28 |
34 |
35 |
--------------------------------------------------------------------------------
/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_main.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
12 |
17 |
18 |
23 |
24 |
29 |
30 |
35 |
36 |
--------------------------------------------------------------------------------
/app/src/main/res/layout/activity_test.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #008577
4 | #00574B
5 | #D81B60
6 |
7 |
--------------------------------------------------------------------------------
/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | AndroidAssert
3 |
4 |
--------------------------------------------------------------------------------
/app/src/main/res/values/styles.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
12 |
13 |
--------------------------------------------------------------------------------
/app/src/test/java/com/it/uncle/androidassert/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.it.uncle.androidassert
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 |
3 | buildscript {
4 | ext.kotlin_version = '1.3.41'
5 | repositories {
6 | google()
7 | jcenter()
8 |
9 | }
10 | dependencies {
11 | classpath 'com.android.tools.build:gradle:3.5.0'
12 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13 | classpath 'com.novoda:bintray-release:0.9.2'
14 | // NOTE: Do not place your application dependencies here; they belong
15 | // in the individual module build.gradle files
16 | }
17 | }
18 |
19 | allprojects {
20 | repositories {
21 | google()
22 | jcenter()
23 |
24 | }
25 | }
26 |
27 | task clean(type: Delete) {
28 | delete rootProject.buildDir
29 | }
30 |
--------------------------------------------------------------------------------
/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx1536m
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app's APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 |
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Sat May 30 15:15:18 CST 2020
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
7 |
--------------------------------------------------------------------------------
/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/img/assumenosideeffects.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/img/assumenosideeffects.png
--------------------------------------------------------------------------------
/img/debug-release.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/img/debug-release.png
--------------------------------------------------------------------------------
/img/no-assumenosideeffects.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/img/no-assumenosideeffects.png
--------------------------------------------------------------------------------
/lib-android-assert/.gitignore:
--------------------------------------------------------------------------------
1 | /build
2 |
--------------------------------------------------------------------------------
/lib-android-assert/build.gradle:
--------------------------------------------------------------------------------
1 | apply plugin: 'com.android.library'
2 |
3 | android {
4 | compileSdkVersion 28
5 |
6 |
7 | defaultConfig {
8 | minSdkVersion 14
9 | targetSdkVersion 28
10 | versionCode 1
11 | versionName "1.0"
12 |
13 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
14 | consumerProguardFiles 'consumer-rules.pro'
15 | }
16 |
17 | buildTypes {
18 | release {
19 | minifyEnabled false
20 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
21 | }
22 | }
23 |
24 | }
25 |
26 | dependencies {
27 | implementation fileTree(dir: 'libs', include: ['*.jar'])
28 |
29 | implementation 'androidx.appcompat:appcompat:1.1.0'
30 | implementation 'junit:junit:4.12'
31 | testImplementation 'junit:junit:4.12'
32 | androidTestImplementation 'androidx.test:runner:1.2.0'
33 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
34 | }
35 |
36 |
37 | //jcenter 配置
38 | apply plugin: 'com.novoda.bintray-release'
39 |
40 | publish {
41 |
42 | def groupProjectID = 'com.ituncle'
43 | def artifactProjectID = 'android-assert'
44 | def publishVersionID = '0.0.2'
45 |
46 | userOrg = 'vectorzeng'
47 | repoName = 'maven'
48 | groupId = groupProjectID
49 | artifactId = artifactProjectID
50 | publishVersion = publishVersionID
51 | desc = 'android开发工具类Assert'
52 | website = 'https://github.com/AITUncle/AndroidAssert'
53 | }
--------------------------------------------------------------------------------
/lib-android-assert/consumer-rules.pro:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AITUncle/AndroidAssert/14aa9c5caee369519555df52795e9e4aad569e05/lib-android-assert/consumer-rules.pro
--------------------------------------------------------------------------------
/lib-android-assert/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 |
--------------------------------------------------------------------------------
/lib-android-assert/src/androidTest/java/com/it/uncle/lib/androidassert/ExampleInstrumentedTest.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.lib.androidassert;
2 |
3 | import android.content.Context;
4 |
5 | import androidx.test.platform.app.InstrumentationRegistry;
6 | import androidx.test.ext.junit.runners.AndroidJUnit4;
7 |
8 | import org.junit.Test;
9 | import org.junit.runner.RunWith;
10 |
11 | import static org.junit.Assert.*;
12 |
13 | /**
14 | * Instrumented test, which will execute on an Android device.
15 | *
16 | * @see Testing documentation
17 | */
18 | @RunWith(AndroidJUnit4.class)
19 | public class ExampleInstrumentedTest {
20 | @Test
21 | public void useAppContext() {
22 | // Context of the app under test.
23 | Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();
24 |
25 | assertEquals("com.it.uncle.lib.androidassert.test", appContext.getPackageName());
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/lib-android-assert/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
3 |
--------------------------------------------------------------------------------
/lib-android-assert/src/main/java/com/it/uncle/lib/util/AndroidAssert.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.lib.util;
2 |
3 |
4 | import junit.framework.AssertionFailedError;
5 | import junit.framework.ComparisonFailure;
6 |
7 | /**
8 | * Android断言工具类
9 | *
10 | * @author vectorzeng
11 | */
12 | public class AndroidAssert {
13 |
14 | private static boolean isEnableThrowError = false;
15 |
16 | /**
17 | * 尽早调用,建议在Application#onCreate的时候调用。
18 | *
19 | * @param enable 当断言失败时,是否抛出异常 AssertionFailedError
20 | */
21 | public static void enableThrowError(boolean enable) {
22 | isEnableThrowError = enable;
23 | }
24 |
25 |
26 | /**
27 | * Fails a test with no message.
28 | *
29 | * 抛出断言异常
30 | */
31 | public static void fail() {
32 | fail(null);
33 | }
34 |
35 | /**
36 | * Fails a test with the given message.
37 | *
38 | * 抛出断言异常
39 | */
40 | public static void fail(String message) {
41 | if (isEnableThrowError) {
42 | throw new AssertionFailedError(message);
43 | }
44 | }
45 |
46 |
47 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ thread ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
48 |
49 | /**
50 | * 检查当前是否是子线程,如果不是,抛出断言异常
51 | */
52 | public static void assertSubThread() {
53 | assertTrue(ThreadTypeUtil.isSubThread());
54 | }
55 |
56 | /**
57 | * 检查当前是否是主线程,如果不是,抛出断言异常
58 | */
59 | public static void assertMainThread() {
60 | assertTrue(ThreadTypeUtil.isMainThread());
61 | }
62 |
63 | /////// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ thread ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
64 |
65 |
66 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ null or nunNull ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
67 |
68 | /**
69 | * Asserts that an object isn't null.
70 | *
71 | * 检查object是否为为非空,如果为空,抛出断言异常
72 | */
73 | public static void assertNotNull(Object object) {
74 | assertNotNull(null, object);
75 | }
76 |
77 | /**
78 | * Asserts that an object isn't null. If it is an AssertionFailedError is
79 | * thrown with the given message.
80 | *
81 | * 检查参数object是否为为非空,如果为空,抛出断言异常
82 | */
83 | public static void assertNotNull(String message, Object object) {
84 | assertTrue(message, object != null);
85 | }
86 |
87 | /**
88 | * Asserts that an object is null.
89 | *
90 | * 检查object是否为null,如果不是null,抛出断言异常
91 | */
92 | public static void assertNull(Object object) {
93 | assertNull(null, object);
94 | }
95 |
96 | /**
97 | * Asserts that an object is null. If it is not an AssertionFailedError is
98 | * thrown with the given message.
99 | *
100 | * 检查object是否为null,如果不是null,抛出断言异常
101 | */
102 | public static void assertNull(String message, Object object) {
103 | assertTrue(message, object == null);
104 | }
105 | /////// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ null or nunNull ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
106 |
107 |
108 |
109 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ true or false ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
110 |
111 | /**
112 | * Asserts that a condition is true. If it isn't it throws an
113 | * AssertionFailedError.
114 | *
115 | * @param condition 不是true,将抛出断言异常
116 | */
117 | public static void assertTrue(boolean condition) {
118 | assertTrue(null, condition);
119 | }
120 |
121 | /**
122 | * Asserts that a condition is true. If it isn't it throws an
123 | * AssertionFailedError with the given message.
124 | *
125 | * @param condition 不是true,将抛出断言异常
126 | */
127 | public static void assertTrue(String message, boolean condition) {
128 | if (!condition)
129 | fail(message);
130 | }
131 |
132 | /**
133 | * Asserts that a condition is false. If it isn't it throws an
134 | * AssertionFailedError.
135 | *
136 | * @param condition 不是false,将抛出断言异常
137 | */
138 | public static void assertFalse(boolean condition) {
139 | assertFalse(null, condition);
140 | }
141 |
142 | /**
143 | * Asserts that a condition is false. If it isn't it throws an
144 | * AssertionFailedError with the given message.
145 | *
146 | * @param condition 不是false,将抛出断言异常
147 | */
148 | public static void assertFalse(String message, boolean condition) {
149 | assertTrue(message, !condition);
150 | }
151 |
152 | /////// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ true or false ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
153 |
154 |
155 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ same ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
156 | /**
157 | * Asserts that two objects refer to the same object. If they are not the
158 | * same an AssertionFailedError is thrown.
159 | *
160 | * expected == actual为false,抛出断言异常
161 | */
162 | public static void assertSame(Object expected, Object actual) {
163 | assertSame(null, expected, actual);
164 | }
165 |
166 | /**
167 | * Asserts that two objects refer to the same object. If they are not an
168 | * AssertionFailedError is thrown with the given message.
169 | *
170 | * expected == actual为false,抛出断言异常
171 | */
172 | public static void assertSame(String message, Object expected, Object actual) {
173 | if (expected == actual)
174 | return;
175 | failNotSame(message, expected, actual);
176 | }
177 |
178 | /**
179 | * Asserts that two objects refer to the same object. If they are not the
180 | * same an AssertionFailedError is thrown.
181 | *
182 | * object != actual为false,抛出断言异常
183 | */
184 | public static void assertNotSame(Object expected, Object actual) {
185 | assertNotSame(null, expected, actual);
186 | }
187 |
188 | /**
189 | * Asserts that two objects refer to the same object. If they are not an
190 | * AssertionFailedError is thrown with the given message.
191 | *
192 | * object != actual为false,抛出断言异常
193 | */
194 | public static void assertNotSame(String message, Object expected,
195 | Object actual) {
196 | if (expected == actual)
197 | failSame(message);
198 | }
199 |
200 |
201 | private static void failNotSame(String message, Object expected,
202 | Object actual) {
203 | if (!isEnableThrowError)
204 | return;
205 | String formatted = "";
206 | if (message != null)
207 | formatted = message + " ";
208 | fail(formatted + "expected same:<" + expected + "> was not:<" + actual
209 | + ">");
210 | }
211 |
212 | private static void failSame(String message) {
213 | if (!isEnableThrowError)
214 | return;
215 | String formatted = "";
216 | if (message != null)
217 | formatted = message + " ";
218 | fail(formatted + "expected not same");
219 | }
220 |
221 | /////// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ same ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
222 |
223 |
224 | /////// ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓ equals ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
225 |
226 | /**
227 | * Asserts that two objects are equal. If they are not an
228 | * AssertionFailedError is thrown.
229 | *
230 | * 检查expected、actual两个对象equals是否为true,如果为false那么抛出断言异常
231 | */
232 | public static void assertEquals(Object expected, Object actual) {
233 | assertEquals(null, expected, actual);
234 | }
235 |
236 | /**
237 | * Asserts that two objects are equal. If they are not an
238 | * AssertionFailedError is thrown with the given message.
239 | */
240 | public static void assertEquals(String message, Object expected,
241 | Object actual) {
242 | if (!isEnableThrowError)
243 | return;
244 |
245 | if (expected == null && actual == null)
246 | return;
247 | if (expected != null && expected.equals(actual))
248 | return;
249 | failNotEquals(message, expected, actual);
250 | }
251 |
252 |
253 | /**
254 | * Asserts that two booleans are equal.
255 | *
256 | */
257 | public static void assertEquals(boolean expected, boolean actual) {
258 | assertEquals(null, expected, actual);
259 | }
260 |
261 | /**
262 | * Asserts that two bytes are equal.
263 | *
264 | */
265 | public static void assertEquals(byte expected, byte actual) {
266 | assertEquals(null, expected, actual);
267 | }
268 |
269 | /**
270 | * Asserts that two chars are equal.
271 | */
272 | public static void assertEquals(char expected, char actual) {
273 | assertEquals(null, expected, actual);
274 | }
275 |
276 | /**
277 | * Asserts that two ints are equal.
278 | */
279 | public static void assertEquals(int expected, int actual) {
280 | assertEquals(null, expected, actual);
281 | }
282 |
283 | /**
284 | * Asserts that two longs are equal.
285 | */
286 | public static void assertEquals(long expected, long actual) {
287 | assertEquals(null, expected, actual);
288 | }
289 |
290 | /**
291 | * Asserts that two shorts are equal.
292 | */
293 | public static void assertEquals(short expected, short actual) {
294 | assertEquals(null, expected, actual);
295 | }
296 |
297 | /**
298 | * Asserts that two booleans are equal. If they are not an
299 | * AssertionFailedError is thrown with the given message.
300 | */
301 | public static void assertEquals(String message, boolean expected,
302 | boolean actual) {
303 | if (!isEnableThrowError)
304 | return;
305 | assertEquals(message, Boolean.valueOf(expected), Boolean.valueOf(actual));
306 | }
307 |
308 | /**
309 | * Asserts that two bytes are equal. If they are not an AssertionFailedError
310 | * is thrown with the given message.
311 | */
312 | public static void assertEquals(String message, byte expected, byte actual) {
313 | if (!isEnableThrowError)
314 | return;
315 | assertEquals(message, Byte.valueOf(expected), Byte.valueOf(actual));
316 | }
317 |
318 | /**
319 | * Asserts that two chars are equal. If they are not an AssertionFailedError
320 | * is thrown with the given message.
321 | */
322 | public static void assertEquals(String message, char expected, char actual) {
323 | if (!isEnableThrowError)
324 | return;
325 | assertEquals(message, Character.valueOf(expected), Character.valueOf(actual));
326 | }
327 |
328 | /**
329 | * Asserts that two ints are equal. If they are not an AssertionFailedError
330 | * is thrown with the given message.
331 | */
332 | public static void assertEquals(String message, int expected, int actual) {
333 | if (!isEnableThrowError)
334 | return;
335 | assertEquals(message, Integer.valueOf(expected), Integer.valueOf(actual));
336 | }
337 |
338 | /**
339 | * Asserts that two longs are equal. If they are not an AssertionFailedError
340 | * is thrown with the given message.
341 | */
342 | public static void assertEquals(String message, long expected, long actual) {
343 | if (!isEnableThrowError)
344 | return;
345 | assertEquals(message, Long.valueOf(expected), Long.valueOf(actual));
346 | }
347 |
348 | /**
349 | * Asserts that two shorts are equal. If they are not an
350 | * AssertionFailedError is thrown with the given message.
351 | */
352 | public static void assertEquals(String message, short expected, short actual) {
353 | if (!isEnableThrowError)
354 | return;
355 | assertEquals(message, new Short(expected), new Short(actual));
356 | }
357 |
358 | /**
359 | * Asserts that two Strings are equal.
360 | */
361 | public static void assertEquals(String expected, String actual) {
362 | assertEquals(null, expected, actual);
363 | }
364 |
365 |
366 | /**
367 | * Asserts that two Strings are equal.
368 | */
369 | public static void assertEquals(String message, String expected,
370 | String actual) {
371 | if (!isEnableThrowError)
372 | return;
373 |
374 | if (expected == null && actual == null)
375 | return;
376 | if (expected != null && expected.equals(actual))
377 | return;
378 |
379 | throw new ComparisonFailure(message, expected, actual);
380 | }
381 |
382 |
383 |
384 | private static void failNotEquals(String message, Object expected,
385 | Object actual) {
386 | if (!isEnableThrowError)
387 | return;
388 | fail(format(message, expected, actual));
389 | }
390 |
391 | /**
392 | * Asserts that two doubles are equal concerning a delta. If the expected
393 | * value is infinity then the delta value is ignored.
394 | */
395 | public static void assertEquals(double expected, double actual, double delta) {
396 | assertEquals(null, expected, actual, delta);
397 | }
398 |
399 | /**
400 | * Asserts that two floats are equal concerning a delta. If the expected
401 | * value is infinity then the delta value is ignored.
402 | */
403 | public static void assertEquals(float expected, float actual, float delta) {
404 | assertEquals(null, expected, actual, delta);
405 | }
406 |
407 | /**
408 | * Asserts that two doubles are equal concerning a delta. If they are not an
409 | * AssertionFailedError is thrown with the given message. If the expected
410 | * value is infinity then the delta value is ignored.
411 | */
412 | public static void assertEquals(String message, double expected,
413 | double actual, double delta) {
414 | if (!isEnableThrowError)
415 | return;
416 |
417 | // handle infinity specially since subtracting to infinite values gives
418 | // NaN and the
419 | // the following test fails
420 | if (Double.isInfinite(expected)) {
421 | if (!(expected == actual))
422 | failNotEquals(message, Double.valueOf(expected), Double.valueOf(actual));
423 | } else if (!(Math.abs(expected - actual) <= delta)) // Because
424 | // comparison
425 | // with NaN always
426 | // returns false
427 | failNotEquals(message, Double.valueOf(expected), Double.valueOf(actual));
428 | }
429 |
430 | /**
431 | * Asserts that two floats are equal concerning a delta. If they are not an
432 | * AssertionFailedError is thrown with the given message. If the expected
433 | * value is infinity then the delta value is ignored.
434 | */
435 | public static void assertEquals(String message, float expected,
436 | float actual, float delta) {
437 | if (!isEnableThrowError)
438 | return;
439 |
440 | // handle infinity specially since subtracting to infinite values gives
441 | // NaN and the
442 | // the following test fails
443 | if (Float.isInfinite(expected)) {
444 | if (!(expected == actual))
445 | failNotEquals(message, Float.valueOf(expected), Float.valueOf(actual));
446 | } else if (!(Math.abs(expected - actual) <= delta))
447 | failNotEquals(message, Float.valueOf(expected), Float.valueOf(actual));
448 | }
449 |
450 | /////// ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ equals ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑
451 |
452 |
453 |
454 |
455 |
456 |
457 | private static String format(String message, Object expected, Object actual) {
458 | String formatted = "";
459 | if (message != null)
460 | formatted = message + " ";
461 | return formatted + "expected:<" + expected + "> but was:<" + actual
462 | + ">";
463 | }
464 |
465 | protected AndroidAssert() {
466 | }
467 | }
468 |
--------------------------------------------------------------------------------
/lib-android-assert/src/main/java/com/it/uncle/lib/util/ThreadTypeUtil.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.lib.util;
2 |
3 | import android.os.Looper;
4 |
5 | public class ThreadTypeUtil {
6 |
7 | public static boolean isMainThread() {
8 | return Looper.getMainLooper() == Looper.myLooper();
9 | }
10 |
11 | public static boolean isSubThread() {
12 | return !isMainThread();
13 | }
14 |
15 | }
16 |
--------------------------------------------------------------------------------
/lib-android-assert/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | lib-android-assert
3 |
4 |
--------------------------------------------------------------------------------
/lib-android-assert/src/test/java/com/it/uncle/lib/androidassert/ExampleUnitTest.java:
--------------------------------------------------------------------------------
1 | package com.it.uncle.lib.androidassert;
2 |
3 | import org.junit.Test;
4 |
5 | import static org.junit.Assert.*;
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * @see Testing documentation
11 | */
12 | public class ExampleUnitTest {
13 | @Test
14 | public void addition_isCorrect() {
15 | assertEquals(4, 2 + 2);
16 | }
17 | }
--------------------------------------------------------------------------------
/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app', ':lib-android-assert'
2 | rootProject.name='AndroidAssert'
3 |
--------------------------------------------------------------------------------