I have a unit test where I am mocking java.net.URI
class. Further, I am creating a jMockit NonStrictExpectation
where I am expecting invocation of URI.getPath()
and returning a particular string.
The code being tested invokes URI.getPath()
twice, where I need to send a different string each time.
Here is my actual method under test:
public void validateResource() {
// some code
URI uri = new URI(link1.getHref());
String path1 = uri.getPath();
// some more code
uri = new URI(link2.getHref());
String path2 = uri.getPath();
}
Here is the unit test code:
@Mocked URI uri;
@Test
public void testValidateResource() {
new NonStrictExpectations() {
{
// for the first invocation
uri.getPath(); returns("/resourceGroup/1");
// for the second invocation [was hoping this would work]
uri.getPath(); returns("/resource/2");
}
};
myObject.validateResource();
}
Now, I want "/resource/2"
to be returned from my expectation when the URI.getPath()
is called second time. But it always hits the first expectation and returns "/recourceGroup/1"
. This is my problem.
How do I make it happen? I can't really use StrictExpectations
due to a number of reasons, and will have to stick with NonStrictExpectations
.
Seems like you just need to list uri.getPath()
once, and use the varargs version of returns
...something like this:
uri.getPath(); returns("/resourceGroup/1", "/resourceGroup/2");
This is according to the documentation, anyway...I have not tested it myself.
Multiple consecutive values to return can be recorded for an expectation, by calling the returns(v1, v2, ...) method. Alternatively, the same can be achieved by assigning the result field with a list or array containing the consecutive values.