Powermock验证非静态方法中的私有静态方法调用 [英] Powermock verify private static method call in non static method

查看:2523
本文介绍了Powermock验证非静态方法中的私有静态方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

亲爱的stackoverflow同志,
我再次遇到问题,让特定的PowerMock / Mockito案例起作用。 问题是,我需要验证私有静态方法的调用,该方法是从公共非静态方法调用的。我之前在如何抑制和验证私有静态时发布的类似示例方法调用?

Dear stackoverflow comrades, I again have a problem in getting a specific PowerMock / Mockito case to work. The issue is, that I need to verify the call of a private static method, which is called from a public non-static method. A similar example I posted previously on How to suppress and verify private static method calls?

这是我的代码:

class Factory {

        public String factorObject() throws Exception {
            String s = "Hello Mary Lou";
            checkString(s);
            return s;
        }

        private static void checkString(String s) throws Exception {
            throw new Exception();
        }
    }

这是我的测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factory = mock(Factory.class);
        suppress(method(Factory.class, "checkString", String.class));
        String s = factory.factorObject();
        verifyPrivate(factory, times(8000)).invoke("checkString", anyString());
    }
}

这里的问题是,测试成功,但它不应该。它不应该是因为私有静态方法应该被正确调用1次。但无论我在时间()中放置什么值,它总是将其验证为真... halp :(

The problem here is, that the Test is successful, but it shouldn't be. It shouldn't be because the private static method should be called exactly 1 times. But no matter what value I put in times(), it always verifies it as true... halp :(

推荐答案

确定,我觉得我找到了答案,但这很令人头痛.Rudy给了我最后的暗示使用间谍,但它仍然不是微不足道的(尽管解决方案看起来很容易)。这是完整的解决方案:

Ok, I think I found the answer, but it was a headache. Rudy gave me the final hint with using using a spy, but it was still not trivial (although the solution looks "baby-easy"). Here is the complete solution:

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.powermock.api.mockito.PowerMockito.verifyPrivate;
import static org.powermock.api.mockito.PowerMockito.doNothing;
import static org.powermock.api.mockito.PowerMockito.spy;

@RunWith(PowerMockRunner.class)
@PrepareForTest(Factory.class)
public class Tests extends TestCase {

    public void testFactory() throws Exception {

        Factory factorySpy = spy(new Factory());
        String s = factorySpy.factorObject();
        doNothing().when(factorySpy, "checkString", anyString());
        verifyPrivate(factorySpy, times(1)).invoke("checkString", anyString()); 
    }
}

这篇关于Powermock验证非静态方法中的私有静态方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆