被告知时,Powermock/mockito不会抛出异常

Jan*_*ide 5 java mockito powermock

我会假设以下测试应该通过,但是从不抛出异常.有线索吗?

@RunWith(PowerMockRunner.class)
@PrepareForTest(StaticService.class)
public class TestStuff {

    @Test(expected = IllegalArgumentException.class)
    public void testMockStatic() throws Exception {
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(StaticService.say("hello"));
        verifyStatic();
        StaticService.say("hello");
}
Run Code Online (Sandbox Code Playgroud)

}

Mat*_*man 5

这是因为你正在使用doThrow ...当静态方法的语法不正确时.有几种不同的方法可以解决这个问题,我已在下面的两个单独的测试方法中概述了这些方法.

@RunWith(PowerMockRunner.class)
@PrepareForTest({StaticService.class})
public class StaticServiceTest {

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic1() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class, "say", Matchers.eq(sayString));
        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

    @Test (expected = IllegalArgumentException.class)
    public void testMockStatic2() throws Exception {
        String sayString = "hello";
        mockStatic(StaticService.class);
        doThrow(new IllegalArgumentException("Mockerror")).when(
            StaticService.class);
        StaticService.say(Matchers.eq(sayString)); //Using the Matchers.eq() is
                                                   //optional in this case.

        //Do NOT use verifyStatic() here. The method hasn't actually been
        //invoked yet; you've only established the mock behavior. You shouldn't
        //need to "verify" in this case anyway.

        StaticService.say(sayString);
        fail("Expected exception not thrown.");
    }

}
Run Code Online (Sandbox Code Playgroud)

作为参考,这是我创建的StaticService实现.我不知道它是否与你的匹配,但我确实验证了测试通过.

public class StaticService {
    public static void say(String arg) {
        System.out.println("Say: " + arg);
    }
}
Run Code Online (Sandbox Code Playgroud)

也可以看看