I'm trying to test my Utils class. Some of the methods use other class methods. I want to mock the internal methods use so the test will assume they work (in order to make it real Unit test, which test the specific method).
I want to test 'buildUrl' method:
public static String buildUrl(String path, List<Pair> queryParams, DateFormat dateFormat) {
final StringBuilder url = new StringBuilder();
url.append(path);
if (queryParams != null && !queryParams.isEmpty()) {
// support (constant) query string in `path`, e.g. "/posts?draft=1"
String prefix = path.contains("?") ? "&" : "?";
for (Pair param : queryParams) {
if (param.getValue() != null) {
if (prefix != null) {
url.append(prefix);
prefix = null;
} else {
url.append("&");
}
String value = Utils.parameterToString(param.getValue(), dateFormat);
url.append(Utils.escapeString(param.getName())).append("=").append(Utils.escapeString(value));
}
}
}
return url.toString();
}
BuildUrl uses 'parameterToString' (and others) which I want to mock for the test. So I tried something like this:
@Test
public void testBuildUrl(){
Utils util = new Utils();
Utils utilSpy = Mockito.spy(util);
Mockito.when(utilSpy.parameterToString("value1",new RFC3339DateFormat())).thenReturn("value1");
List<Pair> queryParams = new ArrayList<Pair>();
queryParams.add(new Pair("key1","value1"));
String myUrl = utilSpy.buildUrl("this/is/my/path", queryParams, new RFC3339DateFormat());
assertEquals("this/is/my/path?key1=value1&key2=value2", myUrl);
}
But I'm getting MissingMethodInvocationException
from Mockito.
So my question is actually - how to mock a method that has been invoked within the tested method, and what's wrong with my test. Thanks.