使用Powermockito断言静态方法的参数值

时间:2015-08-12 11:20:07

标签: java unit-testing powermockito

我的简化类文件如下所示:

M,N,R = raster.shape
linear_indx = R*np.arange(M*N)[:,None] + indx.reshape(M*N,-1)
out = raster.ravel()[linear_indx].reshape(indx.shape)

我正在编写一个junit测试类来测试方法public class NotificationHelper{ public static void sendNotification(String id){ switch (id) { case mobile: String message = "Created new account" break; case email: String message = "Hi, An account is created with our website using your email id. This is a notification regarding the same." break; default: throw new Exception("id is neither phone number nor email id"); } notify(id, message); } public static void notify(String id, String message){ //Code to send notification } } ,同时模拟notify方法。目标是断言传递给sendNotification方法的id和消息变量的值。

1 个答案:

答案 0 :(得分:1)

您需要创建spy。使用mockito API:

@RunWith(PowerMockRunner.class)
@PrepareForTest(NotificationHelper.class)
@PowerMockRunnerDelegate(PowerMockRunnerDelegate.DefaultJUnitRunner.class) // for @Rule
public class NotificationHelperTest {
    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Before
    public void setUp() throws Exception {
        PowerMockito.spy(NotificationHelper.class);
    }

    @Test
    public void testSendNotificationForEmail() throws Exception {
        NotificationHelper.sendNotification("email");

        PowerMockito.verifyStatic();
        NotificationHelper.notify("email", "Hi, An account is created with our website using your email id. This is a notification regarding the same.");
    }

    @Test
    public void testSendNotificationForMobile() throws Exception {
        NotificationHelper.sendNotification("mobile");

        PowerMockito.verifyStatic();
        NotificationHelper.notify("mobile", "Created new account");
    }

    @Test
    public void testSendNotification() throws Exception {
        this.expectedException.expect(Exception.class);
        this.expectedException.expectMessage("id is neither phone number nor email id");
        NotificationHelper.sendNotification("foobar");
    }
}

请注意,我确实更正了您的NotificationHelper

public class NotificationHelper {
    public static void sendNotification(String id) throws Exception {
        // TODO: use an enum
        String message;
        switch (id) {
            case "mobile":
                message = "Created new account";
                break;
            case "email":
                message = "Hi, An account is created with our website using your email id. This is a notification regarding the same.";
                break;
            default:
                throw new Exception("id is neither phone number nor email id");
        }
        notify(id, message);
    }

    public static void notify(String id, String message){
        //Code to send notification
    }
}

使用 PowerMock 1.6.2进行测试

另请注意,如果您避免static,则测试总是方式