JUnit test suite sample code for Android

In this tutorial, we will create a Calculator class in app/src/main/java with two static methods for additino and multiplication. And then create two test classes in app/src/test/java to test the two static methods in the calculator class. And finally we will create a test suite class which will include those two test class and when it runs, it will run both of those test classes.

Before creating any code, let make sure you have the junit in you gradle dependencies. So it looks like this:

dependencies {
    //Other dependencies.....
    //junit test compile dependency
    testCompile 'junit:junit:4.12'
}

1. Create Calaculator.java in your main android package.

public class Calculator {

    public static int addition(int a, int b) {
        return a + b;
    }

    public static int multiplication(int a, int b) {
        return a * b;
    }

}

2. Create AdditionTest.java in your test package. To make this package visible, you need to change the Build Variants to Unit Tests. All the test classes will be under this package.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import static org.junit.Assert.*;
public class AdditionTest {
    @Test
    public void additionTest() throws Exception {
        //Fail this on purpose
        int expected = 5;
        int actual = Calculator.addition(2, 2);
        assertEquals(expected, actual);
    }
}

3. Create MultiplicationTest.java in your test package.

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import static org.junit.Assert.*;

public class MultiplicationTest {
    @Test
    public void multiplicationTest() throws Exception {
        int expected = 6;
        int actual = Calculator.multiplication(2, 3);
        assertEquals(expected, actual);
    }
}

4. Finally, the exciting part, including the above two tests in one test suite so you can run them all at once. Let’s create the Test suite class MyTestSuite.java

import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
        AdditionTest.class,
        MultiplicationTest.class
})
public class MyTestSuite {
}

4. Run it by right click the MyTestSuite class and click run.

5. Run it on command line window in your android project root folder. Tf you run it on the comman line, you don’t even need the MyTestSuite class.

./gradlew test

Search within Codexpedia

Custom Search

Search the entire web

Custom Search