【问题标题】:PowerMockito verifyTimes Always passets private methodPowerMockito verifyTimes 始终传递私有方法
【发布时间】:2021-12-22 17:14:07
【问题描述】:
public class TestedClass
{
    
    public void publicMethod() 
    {
        privateMethod();
    }
    
    private void privateMethod() 
    {
    }
}

我想用 PowerMockito 测试私有方法只被调用一次。

这是我的测试类:

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class TestedClassTest
{
    
    @Before
    public void setUp()
    {
    }
    
    @Test
    public void testPrivateMethodCalledOnce() throws Exception 
    {
        TestedClass spy = PowerMockito.spy(new TestedClass());
        spy.publicMethod();
        
        PowerMockito.verifyPrivate(spy, Mockito.times(772)).invoke("privateMethod"); 
    }
}

尽管仅在此测试通过后才被调用。即使我在公共方法中评论 privateMethod,测试似乎也通过了。

public class TestedClass
{

    public void publicMethod() 
    {
        //privateMethod(); <-- test still passes
    }

    private void privateMethod() 
    {
    }
}

有人知道我做错了什么吗?有谁知道如何验证私有方法在单元测试中被调用了一次吗?

【问题讨论】:

标签: java mockito powermockito spy


【解决方案1】:

似乎我需要在此特定测试中包含 @PrepareForTest 注释以使其工作。现在测试失败了,它应该做的。另外 - 当我更改为 Mockito.times(1) 时它可以工作。

@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
@PrepareForTest(TestedClass.class) // <--- I didn't include this in the question
public class TestedClassTest
{
    
    @Before
    public void setUp()
    {
    }
    
    @Test
    public void testPrivateMethodCalledOnce() throws Exception 
    {
        TestedClass spy = PowerMockito.spy(new TestedClass());
        spy.publicMethod();
        
        PowerMockito.verifyPrivate(spy, Mockito.times(1)).invoke("privateMethod"); 
    }
}

【讨论】:

    【解决方案2】:

    问题可能是,即:

    .invoke("privateMethod")
    

    可以解释为:

    1. void invoke(String methodToVerify, Object... arguments)javadoc,这是我们(显然)想要的。或者
    2. void invoke(Object... arguments)javadoc,这是不同的,它发现(私有)方法不是通过名称,而是通过“参数”。

    所以一个解决方案可能是(避免不正确的过载):

    .invoke("privateMethod", new Object[0]) // which still *could* be 
       // confused with Object... but I "hope" the String in front saves us!:)
    // if this works: .invoke("privateMethod", null) should also work.
    

    或者直接使用其中一种替代方法。#


    但这经常是“重载库”的问题......可变参数使事情变得更糟/可能是不确定的! :-)

    【讨论】:

    • @all: 注意 (Power)Mockito 方法(匹配器/验证器)重载!!
    • 感谢您的回复。真的从你的例子中学到了。在这种情况下,测试中似乎缺少“@PrepareForTest”注释。
    • 其实我完全错了! :-):-):-) 还是谢谢你!
    • 好吧,我学到了一些新东西,而且你没有给我讲课为什么测试私人 1234562 是错误的 =)。还是谢谢
    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 2015-03-23
    • 2014-09-21
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多