First, the use Android Sutdio own code optimized code inspection tool Analyze
1, start Android Studio, in the toolbar above the page can be found Analyze
2, Inspect Code: Check Code
After clicking, and you need to select a range of policy checks.
Check range: entire project, app Module, the main Activity, custom region, including whether the test resource.
After running Inspect Code, can be seen to generate a lot of mistakes, but these problems do not affect the normal operation, but will affect the performance or the size of apk, so the need for code optimization.
(1) Android-> Lint error is displayed:
Accessibility,Correctness,Internationalization,Performance,Security,Usability
Right panel will give the wrong solution:
(2) Internationalization: Internationalization
(3) Performance: Performance
(4) Security: Security
AllowBackup / FullBackupContent Problems: Do not open, when allowBackup flag is true, users can to backup and restore application data, may bring some security risk by adb backup and adb restore.
(5) Class structure: code structure
(6) Spelling: spelling error
(7)XML:
Note: Xml optimization includes tag empty body, such as namespace declarations are not used.
3, Code Cleanup: code cleanup
4, Run Inspection by name: the name of the use of checks to be checked
Find all definitions not being used:
5, infer nullity: a null position may be inferred
6, in addition, can click Code when using the Inspect the Custom scope defined checks range
Project Files: All project files
Project Production Files:项目的代码文件
Project Test Files:项目的测试文件
OpenFiles:当前打开的文件
Module ‘app’:主要的 app 模块
Current File:当前文件
除了内置的选项我们还可以自己选择特定的类进行检查。
点击选择框右侧“…”,会弹出自定义范围选择框,默认是空的,我们可以点击左上角的“+”号新增一个检查范围:
Local:只能当前项目使用
Shared:其他 Android Studio 项目也可以使用
之后就可以点击左边的 app 文件夹,再点击右边的 Include Recursively 按钮,选择APP内的文件进行扫描测试。
二、Android Studio中使用junit做单元测试
1、首先,在工程添加junit依赖。在App目录下的build.gradle中添加依赖:“testCompile 'junit:junit:4+'”
2、打开需要测试的JAVA文件,“右键”->选择“Go To”->"Test"
这时会跳出一个对话框:
3、点击“Create New Test”可以得到引导对话框
此外,也可以通过选择类名,并按“alt + enter”快捷键,在弹出提示框后选择“Create Test”并按“enter”键打开引导对话框:
可以在“Create Test”面板中指定生成setUp方法和tearDown方法,选择需要测试的方法后点击0K:
4、选择生成代码的目标目录
若需要使用到Android系统提供的库的测试代码就选择AndroidTest目录,若只需要Java原声的目录就可以完成所有逻辑就选择test目录,后面的包名系统会自动生成。此处我选择test目录,并点击OK:
生成了一个新的Class文件,文件中有三个方法(setup、tearDown、Oncreate),其中setUp和tearDown是之前选择的方法。
5、在文件中添加测试代码后,选中此文件,右键->选择“ Run ‘文件名’ ”
6、控制台输出测试结果: