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);
}
}
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.
To call a real method of a mock object in Mockito we use the thenCallRealMethod() method.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With