【问题标题】:Mockito - test method inside a nethodMockito - 方法内的测试方法
【发布时间】:2017-07-22 03:33:54
【问题描述】:

我正在尝试测试我的 Utils 类。一些方法使用其他类方法。我想模拟使用的内部方法,以便测试假设它们有效(为了使其成为真正的单元测试,它测试特定的方法)。

我想测试'buildUrl'方法:

 public static String buildUrl(String path, List<Pair> queryParams, DateFormat dateFormat) {
    final StringBuilder url = new StringBuilder();
    url.append(path);

    if (queryParams != null && !queryParams.isEmpty()) {
        // support (constant) query string in `path`, e.g. "/posts?draft=1"
        String prefix = path.contains("?") ? "&" : "?";
        for (Pair param : queryParams) {
            if (param.getValue() != null) {
                if (prefix != null) {
                    url.append(prefix);
                    prefix = null;
                } else {
                    url.append("&");
                }
                String value = Utils.parameterToString(param.getValue(), dateFormat);
                url.append(Utils.escapeString(param.getName())).append("=").append(Utils.escapeString(value));
            }
        }
    }

    return url.toString();
}

BuildUrl 使用我想为测试模拟的“parameterToString”(和其他)。所以我尝试了这样的事情:

 @Test
public void testBuildUrl(){
    Utils util = new Utils();
    Utils utilSpy = Mockito.spy(util);
    Mockito.when(utilSpy.parameterToString("value1",new RFC3339DateFormat())).thenReturn("value1");
    List<Pair> queryParams = new ArrayList<Pair>();
    queryParams.add(new Pair("key1","value1"));
    String myUrl = utilSpy.buildUrl("this/is/my/path", queryParams, new RFC3339DateFormat());
    assertEquals("this/is/my/path?key1=value1&key2=value2", myUrl);
}

但我从 Mockito 收到了 MissingMethodInvocationException。 所以我的问题实际上是 - 如何模拟已在测试方法中调用的方法,以及我的测试有什么问题。谢谢。

【问题讨论】:

    标签: java unit-testing junit mockito powermockito


    【解决方案1】:

    您不能使用标准 Mockito 模拟/监视静态调用。

    您必须使用 Powermockito 和以下内容:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Utils.class)    
    public class MyClassTest{
    
        @Test
        public void testBuildUrl(){
             PowerMockito.mockStatic(Utils.class);
    
             // mock the static method to return certain values
             Mockito.when(Utils.parameterToString("value1",new RFC3339DateFormat()))
                 .thenReturn("value1");
             Mockito.when(Utils.escapeString(anyString()).thenReturn(desiredResult);
    
           // rest of test code
        }
    

    这里还有一些需要阅读的内容 -> powermockito static

    【讨论】:

      【解决方案2】:

      我想模拟使用的内部方法,以便测试假设它们有效(为了使其成为真正的单元测试,它测试特定方法)。

      UnitTests 测试特定方法

      UnitTests 测试被测代码的公共可观察行为


      如果您觉得应该模拟某些方法,这可能表明您的设计需要改进。没有必要创建实用方法static,也许你的被测类有很多责任。

      当然,PowerMock 会克服测试中的问题,但恕我直言,使用 PowerMock 是对糟糕设计的投降。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-27
        • 2012-02-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多