How to test a method returns boolean in Mockito

user2121 picture user2121 · Sep 16, 2017 · Viewed 14.4k times · Source

I am learning how to unit-testing in android studio. As shown below, I have a method called "isValidUrl" and in the testing section below, I coded the testing of that method using Mockito, but the test always fails.

Can you please help and guild me how to test this method?

code

public boolean isValidUrl(String url) {
    return (url != null && !url.equals("")) ? true : false;
}

testing:

public class ValidationTest {
@Mock
private Context mCtx = null;

@Before
public void setUp() throws Exception {
    mCtx = Mockito.mock(Context.class);
    Assert.assertNotNull("Context is not null", mCtx);
}

@Test
public void isValidUrl() throws Exception {
    Validation validation = new Validation(mCtx);
    String url = null;
    Mockito.when(validation.isValidUrl(url)).thenReturn(false);
}

}

Answer

fweigl picture fweigl · Sep 17, 2017

You are getting an exception because you're trying to mock the behaviour of a 'real' object (validation).

You need to separate two things: mocking and asserting.

Mocking means creating 'fake' objects of a class (like you did with Context) and defining their behaviour before the test. In your case

 Mockito.when(validation.isValidUrl(url)).thenReturn(false);

means, you tell the validation object to returns false if isValidUrl(url) is called. You can only do that with mocked objects though, and in your case there's no point in doing that anyway, because you want to test the 'real' behaviour of your Validation class, not the behaviour of a mocked object. Mocking methods is usually used to define the behaviour of the dependencies of the class, in this case, again, the Context. For your test right here, this will not be necessary.

Asserting then does the actual 'test' of how the class under test should behave.

You want to test that isValid() return false for an url that is null:

Assert.assertEquals(validation.isValid(null), false); 

or shorter:

Assert.assertFalse(validation.isValid(null)); 

You can use assertEquals, assertFalse, assertTrue and some others to verify that your isValid() method returns what you want it to return for a given url parameter.