您需要创建一个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
.