Reputation: 113
My simplified class file looks like this:
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
}
}
I am writing a junit test class to test the method sendNotification
while mocking the notify method. The goal is to assert values of id and message variables which are passed to notify
method.
Upvotes: 1
Views: 172
Reputation:
You need to create a spy. With the 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");
}
}
Note that I did correct your 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
}
}
Tested with PowerMock 1.6.2
Also note that testing is always way much easier if you avoid static
.
Upvotes: 1