Testing in Android : Part 2 : Using Hamcrest

How to create a simple Unit Test :  
  1. Open the application we have used in our last tutorial, create one new class “AdditionTest.java” and add the following method :

    @Test
    public void addition_isCorrect() throws Exception {
        assertEquals(4, 2 + 2);
    }

    @Testis used to indicate that this method is a unit test method

  2. Now right click on the method and click on “Run “addition_isCorrect()”

  3. One bottom window will be open inside “Android Studio” and you can see that the test result . If everything goes fine, you will see your test method name with a green button as “OK”
    .android unitTesting
  4. You can add new test methods inside this class or you can add multiple test classes.
Using Hamcrest :
Hamcrest framework is used for checking conditions in code via existing matchers classes . assertThat  statement is used followed by different matchers in JUnit.

JUnit4 :

assertEquals(expected,actual)

Hamcrest :

assertThat(actual,equalTo(expected))
assertThat(actual,is(expected))
assertThat(actual,is(equalTo(expected)))

How to use Hamcrest :

To use Hamcrest in Android Studio, include the following in dependencies tab of your build.gradle file

testCompile 'org.hamcrest:hamcrest-library:1.3'

Sync your project and modify the addition_isCorrect() method of AdditionTest class as below : 

@Test
public void addition_isCorrect() throws Exception {
    assertEquals(4, 2 + 2);

    assertThat(2+2,is(4));
    assertThat(2+2,equalTo(4));
    assertThat(2+2,is(equalTo(4)));
}

Don’t forget to import the following :

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
Run your test  , and you can see that all tests will execute as before.
This project is shared on Github . You can pull it from here.
Check here  for more tutorials on Hamcrest.

Leave a Reply