Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue when unit testing a service using Thymeleaf template Engine

I got a nullPointerException when unit testing my service and i do not understand why? I m using Spring boot. This is my simple service which provide Templating. I autowired TemplateEngine Component.

@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);
    }

}

The unit test of this class is below:

@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");
    }
}

In this test class, the templateEngine variable mocked return null, and then i got nullPointerException when doing this "when(templateEngine.process("TemplateName", refEq(context))).thenReturn("Html template result");"

Please can you help me? i really do not unsderstand why.

like image 267
rostow Avatar asked Apr 27 '17 11:04

rostow


1 Answers

Instead of

@Autowired
private TemplateEngine templateEngine;

use this interface in your Service.

import org.thymeleaf.ITemplateEngine;

@Autowired
private ITemplateEngine templateEngine;

And in your test class use same class as a Mock

@Mock
private ITemplateEngine emailTemplateEngine;

@Before
public void setup(){
    @when(emailTemplateEngine.process(eq(TEMPLATE_USER_CREATION), any(Context.class))).thenReturn(userCreationHtml);
     .
     .
     .
}
like image 125
cazador Avatar answered Sep 26 '22 14:09

cazador