Android Unit testing in Android with JUnit edit

Creating Local unit tests

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:


Table Of Contents
39 ACRA
64 Menu
80 Unit testing in Android with JUnit
112 Loader
119 Xposed
132 Colors
135 Fresco
140 AdMob
147 Button
156 Vk SDK
170 XMPP
176 OpenCV
200 FileIO
203 Moshi
217 Paint
231 AIDL
241 JCodec
243 Okio
255 Looper
  ↑ ↓ to navigate     ↵ to select     Esc to close