Creating Local unit tests

suggest change

Place your test classes here: /src/test/<pkg_name>/

Example test class

public class ExampleUnitTest {
    @Test
    public void addition_isCorrect() throws Exception {
        int a=4, b=5, c;
        c = a + b;
        assertEquals(9, c); // This test passes
        assertEquals(10, c); //Test fails
    }
}

Breakdown

public class ExampleUnitTest {
  ...
}

The test class, you can create several test classes and place them inside the test package.

@Test
public void addition_isCorrect() {
   ...
}

The test method, several test methods can be created inside a test class.

Notice the annotation @Test.

The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case.

There are several other useful annotations like @Before, @After etc. This page would be a good place to start.

assertEquals(9, c); // This test passes
assertEquals(10, c); //Test fails

These methods are member of the Assert class. Some other useful methods are assertFalse(), assertNotNull(), assertTrue etc. Here’s an elaborate Explanation.


Annotation Information for JUnit Test:

@Test: The Test annotation tells JUnit that the public void method to which it is attached can be run as a test case. To run the method, JUnit first constructs a fresh instance of the class then invokes the annotated method.

@Before: When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void method with @Before causes that method to be run before the Test method.

@After: If you allocate external resources in a Before method you need to release them after the test runs. Annotating a public void method with @After causes that method to be run after the Test method. All @After methods are guaranteed to run even if a Before or Test method throws an exception


Tip Quickly create test classes in Android Studio

Tip Easily execute tests in Android Studio

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Unit testing in Android with JUnit:
* Creating Local unit tests

Table Of Contents
2 Gradle
5 Intent
17 Service
19 WebView
31 SQLite
35 Glide
37 Dialog
38 ACRA
44 Handler
53 Toast
63 Menu
65 Picasso
70 Volley
71 Widgets
78 Realm
79 Unit testing in Android with JUnit
90 Spinner
95 OkHttp
108 TextView
109 ListView
111 Loader
118 Xposed
119 Security
121 ImageView
123 Doze Mode
130 Drawables
131 Colors
134 Fresco
139 AdMob
145 Keyboard
146 Button
150 EditText
155 Vk SDK
163 ExoPlayer
169 XMPP
175 OpenCV
177 Threads
184 ORMLite
186 TabLayout
190 LruCache
192 Zip files
194 Fastlane
199 FileIO
202 Moshi
210 VideoView
216 Paint
218 ProGuard
226 CleverTap
228 ADB shell
229 Ping ICMP
230 AIDL
234 Context
240 JCodec
242 Okio
249 FuseView
254 Looper
261 Fastjson
263 Jackson
267 Smartcard