6

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

}

Masoud Mokhtari
  • 2,390
  • 1
  • 17
  • 45
Amrmsmb
  • 1
  • 27
  • 104
  • 226

1 Answers1

10

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.

fweigl
  • 21,278
  • 20
  • 114
  • 205
  • thank you for your answer..but can i use more than one Assert in the same method..because i want to test isValid(null), isValid(true) and isValid(false) – Amrmsmb Sep 17 '17 at 09:07
  • 1
    @user2121 Yes you can. It's a matter of taste, most people would recommend you to do an extra test method for each of those cases, but you can also do as many assertions as you like in one test method. – fweigl Sep 17 '17 at 09:15
  • thanks..i posted another question related to testing here:https://stackoverflow.com/questions/46262467/how-to-test-picasso-using-unit-test-and-mockito maybe you want to have a look, and your answer will be a guiding line for me and as a tutorial as well because i am learning testing units – Amrmsmb Sep 17 '17 at 09:21