I have following @Service
class that is used to receive feedback, verify its details based on a list of criteria. If verified send that to its recipient.
I am struggling to write a test case for this class. I know there is no need to test external services using Junit. Like sending email in my case but,
- Whats the best approach to test this class?
- Should I even test it?
- If not why?
- If yes how to complete the test case?
Code
@Service
public class FeedbackServiceImpl implements FeedbackService {
@Autowired
private MailSender mailSender;
@Override
public boolean sendIt(Feedback feedback)
throws MailAuthenticationException, CustomException {
validateEmail(feedback.getEmail());
try {
SimpleMailMessage message = new SimpleMailMessage();
switch (feedback.getRecipient()) {
case 1:
message.setTo("jack@project.com");
break;
case 2:
message.setTo("norman@project.com");
break;
default:
message.setTo("hello@project.com");
break;
}
message.setCc(feedback.getEmail());
message.setSubject(subject);
message.setText(msg);
mailSender.send(message);
} catch (MailSendException send) {
System.err.println(send.getFailedMessages() + " "
+ send.getMessage() + " " + feedback);
}
return true;
}
private void validateEmail(String sender) throws CustomException {
//make sure provided email is valid
//this method does verification process against different criteria
}
}
JUnit
@Test
public void shouldReturnFalseForInvalidFeedbackEmail(){
MailSender mailSender = Mockito.mock(MailSender.class);
FeedbackService feedbackSrv = new FeedbackServiceImpl();
boolean result = feedbackSrv.sendIt(feedback);
assertTrue(result);
}