[英]Asserting argument values of a static method using Powermockito
我的簡化的類文件如下所示:
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方法的同時測試sendNotification
方法。 目的是斷言傳遞給notify
方法的id和消息變量的值。
您需要創建一個間諜 。 使用嘲笑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
,則測試總是容易得多 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.