Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return different values each time from jMockit expectation

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.

like image 753
Nagendra U M Avatar asked Oct 22 '12 18:10

Nagendra U M


1 Answers

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.

like image 81
Jeff Olson Avatar answered Oct 06 '22 23:10

Jeff Olson