Spring 使用 Thymeleaf 的 Boot 1.4 MVC 测试导致 TemplateProcessingException

Spring Boot 1.4 MVC testing with Thymeleaf results in TemplateProcessingException

我正在尝试测试 Spring Boot 1.4.0.M3 MVC 切片。控制器是这个

@Controller
public class ProductController {

private ProductService productService;

@Autowired
public void setProductService(ProductService productService) {
    this.productService = productService;
 }

 @RequestMapping("product/{id}")
 public String showProduct(@PathVariable Integer id, Model model){
    model.addAttribute("product", productService.getProductById(id));
    return "productshow";
 }
}

productshow.html thymeleaf 模板的最小化视图是这样的。

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
 <div class="container">  
  <h2>Product Details</h2>
    <div>
        <form class="form-horizontal">
            <div class="form-group">
                <label class="col-sm-2 control-label">Product Id:</label>
                <div class="col-sm-10">
                    <p class="form-control-static" th:text="${product.id}">Product Id</p></div>
            </div>
            <div class="form-group">
                <label class="col-sm-2 control-label">Description:</label>
                <div class="col-sm-10">
                    <p class="form-control-static" th:text="${product.description}">description</p>
                </div>
            </div>                
        </form>
   </div>
  </div>
</body>
</html>

测试class就是这个

@RunWith(SpringRunner.class)
@WebMvcTest(controllers = ProductController.class, secure = false)
//@AutoConfigureMockMvc(secure=false)
public class ProductControllerTest {
    @Autowired
    private MockMvc mockMvc;
    @MockBean
    private ProductService productServiceMock;

@Test
public void testShowProduct() throws Exception {
   Product product1 = new Product();
   product1.setId(1);
   product1.setDescription("T Shirt");
   product1.setPrice(new BigDecimal("18.95"));
   product1.setImageUrl("https://example.com/wp-content/uploads/2015/04/spring_framework_guru_shirt-rf412049699c14ba5b68bb1c09182bfa2_8nax2_512.jpg");
   when(productServiceMock.getProductById(1)).thenReturn(product1);

   MvcResult result = mockMvc.perform(get("/product/{id}/", 1))
           .andExpect(status().isOk())              
           .andReturn();
 }
}

在 运行 测试中,出现以下错误。

2016-07-03 00:03:29.021 ERROR 6800 --- [           main]  
org.thymeleaf.TemplateEngine             : [THYMELEAF][main] Exception  
processing template "productshow": Exception evaluating SpringEL 
expression: "product.id" (productshow:19)

org.springframework.web.util.NestedServletException: Request processing  
failed; nested exception is 
org.thymeleaf.exceptions.TemplateProcessingException: Exception 
evaluating SpringEL expression: "product.id" (productshow:19)

需要帮助来解决这个问题。提前致谢。

将正确的控制器传递给 @WebMvcTest 解决了该问题。通过 ProductController.class 后编辑的代码正在运行。