静态方法捕获验证

时间:2014-02-05 12:29:51

标签: java jmockit

我无法捕获静态方法的参数。静态方法在测试方法中调用,然后在验证块中第二次调用,但这次参数为null所以我有一个NullPointerException ...

这是我的代码:

@Tested
private Service testService;

@Test
public void test {

    // Tested method
    Deencapsulation.invoke(testService, "testMethod");

    // Verifications
    new Verifications() {
        NotificationsUtils utils;
        {
            HashMap<String, Object> map;
            NotificationsUtils.generateXML(anyString, map = withCapture());

            // NullPointerException is thrown here
            // because in generateXML method map is null and map.entrySet() is used.
        }
    };

}

如何在调用generateXML时捕获map变量?

由于

1 个答案:

答案 0 :(得分:1)

显然,您的测试从未声明NotificationsUtils被嘲笑。 但是,以下完整示例有效:

static class Service {
    void testMethod() {
        Map<String, Object> aMap = new HashMap<String, Object>();
        aMap.put("someKey", "someValue");

        NotificationsUtils.generateXML("test", aMap);
    }
}

static class NotificationsUtils {
    static void generateXML(String s, Map<String, Object> map) {}
}

@Tested Service testService;

@Test
public void test(@Mocked NotificationsUtils utils) {
    Deencapsulation.invoke(testService, "testMethod");

    new Verifications() {{
        Map<String, Object> map;
        NotificationsUtils.generateXML(anyString, map = withCapture());
        assertEquals("someValue", map.get("someKey"));
    }};
}