foreword
When we use Android Studio to create a new project, we will find that there are two directories test and androidTest at the same level as the main directory. These two are the unit test codes, and the androidTest is the Instrumentation test code.
Today we will take a look at the simple use of Instrumentation.
Existing project
The above is the case of a new project. If it is an existing project, how to add unit tests?
First of all, it depends on several related libraries, as follows:
testImplementation 'junit:junit:4.+'
androidTestImplementation 'androidx.test.ext:junit:1.1.2'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
Then add testInstrumentationRunner in build.gradle
android {
compileSdk 31
defaultConfig {
applicationId "com.xxx.junittest"
minSdk 21
targetSdk 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
...
Then create a new directory under the src directory, and directly select the option "androidTest/java" in the creation window.
After creating the directory, create a package (same as the application package name) in this directory, and then you can create a test class to write code.
test class
A simple example is as follows:
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("com.xxxx.junittest", appContext.packageName)
}
}
Here, the application context is obtained through InstrumentationRegistry.getInstrumentation().targetContext , and then the registration is verified.
run test
You can test the entire class, or you can test a single function, as follows
The picture shows the test useAppContext function, the test results are as follows
Because the package name I tested was wrong, the result of this test failed.
Test Activity
Let's look at a more complicated example. We need to open a page, then get a text on the page and check whether it is correct. The code is as follows:
@Test
fun startMain(){
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
val intent = Intent(appContext, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
val activity = InstrumentationRegistry.getInstrumentation().startActivitySync(intent)
val textView = activity.findViewById<TextView>(R.id.textview)
assertEquals("hello", textView.text)
}
Here we use startActivitySync to start the page, then get the TextView whose id is R.id.textview, and check its text.
There was a problem during the test. Running this code has been unsuccessful, and the error is as follows:
java.lang.RuntimeException: Could not launch intent Intent { flg=0x14000000 cmp=com.xxx.junittest/.MainActivity } within 45000 milliseconds. Perhaps the main thread has not gone idle within a reasonable amount of time? There could be an animation or something constantly repainting the screen. Or the activity is doing network calls on creation? See the threaddump logs. For your reference the last time the event queue was idle before your activity launch request was 1651831105045 and now the last time the queue went idle was: 1651831105045. If these numbers are the same your activity might be hogging the event queue.
at androidx.test.runner.MonitoringInstrumentation.startActivitySync(MonitoringInstrumentation.java:490)
…
It was said on the Internet that it was caused by the HotSwap function of Android Studio, but it didn’t work even if it was turned off. In the end, it was found to be a problem with the mobile phone. An error was reported on the Xiaomi mobile phone, and it was fine to replace it with a Huawei mobile phone.
Keep the Activity open
Running the above code can find that the activity is only opened for a moment and then closed. What if we want to keep the activity open to do some operations? In fact, it is very simple, just add a sleep, as follows:
@Test
fun startMain(){
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
val intent = Intent(appContext, MainActivity::class.java)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
InstrumentationRegistry.getInstrumentation().startActivitySync(intent)
sleep(5000)
}
In this way, the page will stay for 5 seconds after opening.
Summarize
In the future, we can use Instrumentation to create more tests in order to improve our application.
at last
If you want to become an architect or want to break through the 20-30K salary range, then don't be limited to coding and business, but you must be able to select models, expand, and improve programming thinking. In addition, a good career plan is also very important, and the habit of learning is very important, but the most important thing is to be able to persevere. Any plan that cannot be implemented consistently is empty talk.
If you have no direction, here I would like to share with you a set of "Advanced Notes on the Eight Major Modules of Android" written by the senior architect of Ali, to help you organize the messy, scattered and fragmented knowledge systematically, so that you can systematically and efficiently Master the various knowledge points of Android development.
Compared with the fragmented content we usually read, the knowledge points of this note are more systematic, easier to understand and remember, and are arranged strictly according to the knowledge system.
Full set of video materials:
1. Interview collection
2. Source code analysis collection
3. The collection of open source frameworks
welcomes everyone to support with one click and three links. If you need the information in the article, just click the CSDN official certification WeChat card at the end of the article to get it for free↓↓↓
![](https://hnxx.oss-cn-shanghai.aliyuncs.com/official/1680501684204.png?t=0.9137202179270518)