0
我試圖測試Spring Boot 1.4.0.M3 MVC切片。控制器是這樣的。Spring Boot 1.4 MVC測試與Thymeleaf導致TemplateProcessingException
@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>
而測試類是這樣的。
@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)
需要幫助來解決這個問題。提前致謝。
如果您調試它,控制器是否真的獲得您的product1 bean?什麼是產品代碼?你有更完整的異常堆棧跟蹤嗎? –
你說得對。控制器沒有獲得'product1',因爲我將錯誤的控制器傳遞給'@ WebMvcTest'。它應該是'ProductController.class'而不是'IndexController.class'。您詳細檢查異常跟蹤的建議有所幫助。謝謝。 – user2693135