1

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

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
}
}

我正在编写一个 junit 测试类来测试该方法sendNotification,同时模拟 notify 方法。目标是断言传递给notify方法的 id 和消息变量的值。

4

1 回答 1

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.

于 2015-08-12T18:08:34.860 回答