Creating Local unit tests
suggest changePlace 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 failsThese 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
- Place the cursor on the class name for which you want to create a test class.
- Press Alt + Enter (Windows).
- Select Create Test, hit Return.
- Select the methods for which you want to create test methods, click OK.
- Select the directory where you want to create the test class.
- You’re done, this what you get is your first test.
Tip Easily execute tests in Android Studio
- Right click test the package.
- Select Run ’Tests in …
- All the tests in the package will be executed at once.