每次从jMockit期望返回不同的值

Nag*_*U M 14 junit jmockit mocking

我有一个单元测试,我在嘲笑java.net.URI课堂.此外,我正在创建一个jMockit NonStrictExpectation,我希望调用URI.getPath()并返回一个特定的字符串.

正在测试的代码调用URI.getPath()两次,我需要每次发送一个不同的字符串.

这是我测试的实际方法:

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();
}
Run Code Online (Sandbox Code Playgroud)

这是单元测试代码:

@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();
}
Run Code Online (Sandbox Code Playgroud)

现在,我想"/resource/2"URI.getPath()第二次被召唤时从我的期望中回归.但它始终达到了第一个期望和回报"/recourceGroup/1".这是我的问题.

我该如何实现?StrictExpectations由于种种原因我无法真正使用,并且必须坚持下去NonStrictExpectations.

Jef*_*son 22

好像你只需要列出uri.getPath()一次,并使用varargs版本returns...这样的东西:

uri.getPath(); returns("/resourceGroup/1", "/resourceGroup/2");
Run Code Online (Sandbox Code Playgroud)

无论如何,这是根据文档 ...我自己没有测试过.

在为给定期望记录多个连续返回值的情况下,可以对return(Object,Object ...)方法进行单次调用.