2017-04-27 60 views
2

單元測試我的服務時出現nullPointerException異常,我不明白爲什麼?我使用Spring引導。 這是我提供模板的簡單服務。我自動裝配了TemplateEngine組件。使用Thymeleaf模板測試服務的單元測試時的問題引擎

@Service 
public class TicketTemplatingService implements ITemplatingService{ 

    @Autowired 
    private TemplateEngine templateEngine; 

    /** 
    * This method will return a ticket template 
    */ 
    @Override 
    public String buildHtmlTemplating(Object object, String templateName) { 
     Ticket ticket= (Ticket)object; 
     //Build the template 
     Context context = new Context(); 
     context.setVariable("id", ticket.getId()); 
     context.setVariable("date", ticket.getDate());   
     return templateEngine.process(templateName, context); 
    } 

} 

這個類的單元測試低於:

@SpringBootTest 
@RunWith(SpringRunner.class) 
@ActiveProfiles("test") 
public class TemplatingServiceTest { 


    @InjectMocks 
    private TicketTemplatingService ticketTemplatingService; 

    @Mock 
    private TemplateEngine templateEngine; 

    @Before 
    public void setup(){ 
     MockitoAnnotations.initMocks(this); 
    } 

    @Test 
    public void testHtmlTemplateReturnTheHtmlTemplate(){ 
     Ticket ticket= new Ticket(); 
     ticket.setId(1L); 
     Date date=new Date(); 
     ticket.setDate(date); 

     Context context=new Context(); 
     context.setVariable("id", 1L); 
     context.setVariable("date", date); 

     //Mock the process method of the templateEngine bean 
     when(templateEngine.process("TemplateName", refEq(context))).thenReturn("Html template result"); 

     //Now we can test the method 
     String htmlTemplate=ticketTemplatingService.buildHtmlTemplating(ticket, "TemplateName"); 
     assertThat(htmlTemplate).isEqualTo("Html template result"); 
    } 
} 

在該試驗中類中,templateEngine可變嘲笑返回零,然後我得到的NullPointerException這樣做時「時(templateEngine.process( 「TemplateName」,refEq(context)))。thenReturn(「Html template result」);「

請幫助我嗎?我真的不明白爲什麼。

回答

0

我在使用Mokito測試thymeleaf模板時遇到同樣的問題。根據我的研究,您可以嘗試:

  1. 檢查您的Thymeleaf罐的版本。如果使用spring-boot-starter-thymeleaf dependecny,它可能仍然使用版本號< 3.0,該版本比當前的穩定版本舊。

根據此鏈接:Final methods in TemplateEngine make it difficult to mock 3.0版本有這樣的問題更好的解決方案。

如果您使用的是3.0+版本,那麼PowerMock可以解救。 參考此鏈接:https://github.com/powermock/powermock/wiki/mockfinal 如何嘲笑最終方法(此鏈接使用了EasyMock)

如果使用< 3.0版,截至目前,唯一的臨時修復,我發現是從第一個鏈接的最後評論在文中。

祝你好運,希望更多的人才能回答這個問題。

1

而不是

@Autowired 
private TemplateEngine templateEngine; 

採用此接口的爲您服務。

import org.thymeleaf.ITemplateEngine; 

@Autowired 
private ITemplateEngine templateEngine; 

並在測試類使用同一個班一個模擬

@Mock 
private ITemplateEngine emailTemplateEngine; 

@Before 
public void setup(){ 
    @when(emailTemplateEngine.process(eq(TEMPLATE_USER_CREATION), any(Context.class))).thenReturn(userCreationHtml); 
    . 
    . 
    . 
}