简体   繁体   English

验证使用 PowerMockito 调用最终类的私有静态方法

[英]Verify private static method on final class gets called using PowerMockito

I have the following class我有以下课程

public final class Foo {
  private Foo() {}
  public static void bar() {
    if(baz("a", "b", new Object())) { }
  }
  private static boolean baz(Object... args) {
    return true;  // slightly abbreviated logic
  }
}

And this is my Test:这是我的测试:

@PrepareOnlyThisForTest(Foo.class)
@RunWith(PowerMockRunner.class)
public class FooTest {
  @Test
  public void bar() {
    PowerMockito.mockStatic(Foo.class); // prepare
    Foo.bar(); // execute
    verifyPrivate(Foo.class, times(1)).invoke("baz", anyVararg()); // verify - fails
  }
}

For that, I get the following error message - and I don't understand why...为此,我收到以下错误消息 - 我不明白为什么......

Wanted but not invoked com.example.Foo.baz( null );通缉但未调用 com.example.Foo.baz( null );

However, there were other interactions with this mock.但是,与此模拟还有其他交互。

Removing the prepare line above seems to make the verify line pass no matter for how many times you check for... :(无论您检查多少times删除上面的prepare行似乎都会使验证行通过... :(

(Our SONAR code checks enforce that each test has some sort of assertXyz() in it (hence the call to verify() ) and enforces a very high test coverage.) (我们的 SONAR 代码检查强制每个测试都包含某种assertXyz() (因此调用verify() )并强制执行非常高的测试覆盖率。)

Any ideas how to do this?任何想法如何做到这一点?

The problem with your code is that you mock Foo so your method implementations won't be called by default such that when you call Foo.call() it does nothing by default which means that it never avtually calls baz that is why you get this behavior.您的代码的问题在于您模拟Foo因此默认情况下不会调用您的方法实现,因此当您调用Foo.call()时,默认情况下它什么都不做,这意味着它永远不会调用baz ,这就是您得到这个的原因行为。 If you want to partially mock Foo , mock it using the option Mockito.CALLS_REAL_METHODS in order to make it call the real methods as you seem to expect, so the code should be:如果您想部分模拟Foo ,请使用选项Mockito.CALLS_REAL_METHODS模拟它,以使其按照您的预期调用真正的方法,因此代码应该是:

@PrepareOnlyThisForTest(Foo.class)
@RunWith(PowerMockRunner.class)
public class FooTest {
    @Test
    public void bar() throws Exception {
        PowerMockito.mockStatic(Foo.class, Mockito.CALLS_REAL_METHODS); // prepare
        ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM