Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test a method returns boolean in Mockito

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);
}

}

like image 277
user2121 Avatar asked Sep 16 '17 21:09

user2121


People also ask

Can we test private method using Mockito?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.

How do you call a real method in Mockito?

To call a real method of a mock object in Mockito we use the thenCallRealMethod() method.

What is the use of Verify in Mockito?

Mockito Verify methods are used to check that certain behavior happened. We can use Mockito verify methods at the end of the testing method code to make sure that specified methods are called.


1 Answers

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.

like image 185
fweigl Avatar answered Sep 27 '22 22:09

fweigl