简体   繁体   English

如何使用 jMockit 和 TestNG 在最终 class 中验证对 static 方法的调用?

[英]How do I verify a call to a static method in a final class using jMockit and TestNG?

How do I verify a call to a static method in a final class using jMockit?如何使用 jMockit 在最终 class 中验证对 static 方法的调用?

In PowerMockito, this isn't possible because the class is final.在 PowerMockito 中,这是不可能的,因为 class 是最终的。 If this can't be done using jMockit, what are the alternatives?如果使用 jMockit 无法做到这一点,有什么替代方案?

You should be able to do it in PowerMockito, yes. 您应该可以在PowerMockito中做到这一点,是的。

Anyway, in JMockit, you usually would write a verification block like the following: 无论如何,在JMockit中,通常会编写如下的验证块:

@Test
public void exampleTest(@Mocked AFinalClass mock)
{
    // Call the code under test which uses AFinalClass.

    new Verifications() {{ AFinalClass.someStaticMethod(); }};
}

Below is my version based on @Mocked and MockUp下面是我基于@MockedMockUp的版本

public class Util {
    static {
        // static initializer
    }

    public static void doSomething(String arg) {
        // do something
    }
}
public class SomeTest {
    @Test
    public void testDoSomething(@Mocked Util util) {
        // NOTE: need to move the `MockUp` to @BeforeClass method if you want to mock the static initializer
        new MockUp<Util>() {
            @Mock
            void $clinit() {
                // do nothing
            }

            @Mock
            void doSomething(String arg) {
                // mock doSomething
            }
        };

        // action to test

        // verify
        new Verifications() {{
            String arg;
            Util.doSomething(arg = withCapture());
            assertEquals("expected", arg);
        }};
    }
}

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

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