Issue
Can somebody make an junit test on this class?
public class MyApplication {
private EmailService email = new EmailService();
public boolean processMessages (String msg , String recipient ) {
if (msg.length ==0 | | recipient.length ==0 ) {
return false ;
}
return this.email.sendEmail (msg , recipient ) ;
}
}
Solution
Your title makes the problem clear: you are not injecting the dependency on EmailService
. To do that, add a setter or (better) make it final
and add it to the constructor.
That'd look like:
public class MyApplication {
private final EmailService email;
public MyApplication(EmailService email) {
this.email = email;
}
public boolean processMessages (String msg , String recipient ) {
if (msg.length == 0 || recipient.length == 0 ) {
return false ;
}
return this.email.sendEmail (msg , recipient ) ;
}
}
And an appropriate test might be (using junit and mockito):
private MyApplication app;
private EmailService email;
@BeforeEach
void setup() {
email = mock(EmailService.class);
when(email.sendEmail(any(), any())).thenReturn(true);
app = new MyApplication(email);
}
@Test
void testProcessZeroLengthMessageOrPerson() {
assertFalse(app.processMessages("", "Person"));
assertFalse(app.processMessages("Message", "")):
assertFalse(app.processMessages("", "")):
}
@Test
void testProcessMessage() {
assertTrue(app.processMessage("Message", "Person"));
verify(email).sendEmail("Message", "Person");
}
Answered By - sprinter