【问题标题】:Return different values each time from jMockit expectation每次从 jMockit 期望返回不同的值
【发布时间】:2012-10-22 18:49:53
【问题描述】:

我有一个单元测试,我在其中模拟 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();
}

单元测试代码如下:

@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();
}

现在,我希望 "/resource/2" 在第二次调用 URI.getPath() 时从我的期望中返回。但它总是达到第一个期望并返回"/recourceGroup/1"。这是我的问题。

我该如何实现?由于多种原因,我不能真正使用StrictExpectations,我必须坚持使用NonStrictExpectations

【问题讨论】:

    标签: junit mocking jmockit


    【解决方案1】:

    似乎您只需要列出一次uri.getPath(),并使用returns 的可变参数版本...类似这样:

    uri.getPath(); returns("/resourceGroup/1", "/resourceGroup/2");
    

    这个是按照documentation的,反正我自己没测试过。

    通过调用returns(v1, v2, ...) 方法,可以为一个期望记录多个要返回的连续值。或者,也可以通过为 result 字段分配包含连续值的列表或数组来实现。

    【讨论】:

      猜你喜欢
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多