I am trying to write junit test against an old sendmail class which uses VelocityEngine and JavaMailSender. There is an anonymous class, it's type is MimeMessagePreparator. The code is as following:
public void send(final String status,final AutoftpTask task,final float localFileSize,final float tranSpd,final float term) {
MimeMessagePreparator preparator = new MimeMessagePreparator() {
public void prepare(MimeMessage mimeMessage) throws Exception {
MimeMessageHelper message = new MimeMessageHelper(mimeMessage);
String subject = "TEST-"+task.getFtpName()+"-"+ status + " " + task.getPkgName() + " [" +
localFileSize + " MB]";
message.setSubject(subject);
message.setTo(task.getOperatorEmail());
message.setFrom("test@test.com"); // could be parameterized...
DecimalFormat myFormatter = new DecimalFormat("####.##");
Map model = new HashMap();
model.put("status", status);
model.put("task", task);
model.put("size", myFormatter.format(localFileSize));
model.put("speed", tranSpd);
model.put("term",term);
model.put("sTime", getTime.getCurrentTime());
String text = VelocityEngineUtils.mergeTemplateIntoString(
velocityEngine, "abc/def/abcMail.vm", model);
message.setText(text, true);
}
};
try{
this.mailSender.send(preparator);
}catch(Exception e){
// log.error(e.getMessage());
e.printStackTrace();
}
}
I want to capture the message.setText(text,true) method which is an instance belongs to the anonymous class and verify the content of that text. That means there are two layers classes need to be faked. After 3 day's trying, i composed the following code to capture the String successfully.
@Test
public <T extends MimeMessagePreparator> void sendTest() throws Exception {
new MockUp<T>(){
@Mock
public void $init(MimeMessageHelper message){
}
@Mock
public void prepare(Invocation invocation,MimeMessage mimeMessage) throws Exception{
new MockUp<MimeMessageHelper>(){
@Mock
public void $init(MimeMessage mimeMessage){
System.out.println(mimeMessage.toString());
}
@Mock
public void setSubject(String text) throws MessagingException {
System.out.println(text);
}
@Mock
public void setText(String text,boolean html) throws MessagingException {
System.out.println(text);
}
};
invocation.proceed(mimeMessage);
}
};
cdeTask.setPkgName("UnitTestPackage.rpm");
cdeTask.setFtpName("ABC");
cdeTask.setOperatorEmail("unit@test.com");
Sendmail sendmail=new Sendmail();
sendmail.setMailSender(mailSender);
sendmail.setVelocityEngine(velocityEngine);
sendmail.send("Success", autoftpTask, 100f,20f,5);
}
}