I have a below test class method that I am writing a test for.
public String doSomething(Dependency dep) {
StringBuilder content = new StringBuilder();
String response;
while ((response = dep.get()) != null) {
content.append(response);
}
return content.toString();
}
Below is the test case I have. Basically I want the Dependency#get()
method to return "content"
in the first iteration and null
in the second.
@Test
void test(@Mocked Dependency dep) {
new Expectations() {
{
dep.get();
result = "content";
times = 1;
}
};
Assertions.assertEquals("content", testSubject.doSomething(dep));
}
However this results in JMockit throwing Unexpected invocation to: Dependency#get()
error. If I remove the times
field, my test runs in a forever loop.
How can I test this method?
So I found out that JMockit apart from the result
paramater can also set a returns(args...)
method to which we can pass a series of arguments that it will expect sequentially. So modifying the test to this worked for me.
@Test
void test(@Mocked Dependency dep) {
new Expectations() {
{
dep.get();
returns("content", null);
times = 2; // limiting to mock only twice as only 2 values are provided in returns
}
};
Assertions.assertEquals("content", testSubject.doSomething(dep));
}