当被告知时,Powermock / mockito不会引发异常 [英] Powermock/mockito does not throw exception when told to

查看:366
本文介绍了当被告知时,Powermock / mockito不会引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我本以为下面的测试应该通过,但是永远不会抛出异常。有什么线索吗?

I would have assumed that the following test should pass, but the exception is never thrown. Any clues ?

@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");
}

}

推荐答案

这是因为您在静态方法中语法错误地使用了doThrow...。我在下面的两个单独的测试方法中概述了几种解决方法。

It's because you are using the doThrow...when syntax incorrectly for static methods. There are a couple different ways to approach this which I've outlined in two separate test methods below.

@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.");
    }

}

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

For reference, here was the StaticService implementation I created. I don't know if it matches yours but I did verify that the tests pass.

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



另请参见



查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆