【发布时间】:2018-09-21 18:41:20
【问题描述】:
我正在尝试测试我的控制器,该控制器采用更新供应商的形式
//get supplier form for update
@GetMapping("/{id}")
public String getSupplierUpdateForm(@PathVariable Long id, Model model) {
if(supplierRepository.findById(id).isPresent()){
model.addAttribute("supplier",supplierRepository.findById(id).get());
}
return "supplier";
}
到目前为止,我能够编写这个测试
@Test
public void testGetSupplierUpdateForm()throws Exception{
Supplier supplier = new Supplier();
supplier.setId((long)1);
supplier.setSupplierName("ABC Company");
supplier.setAddress("Bayombong, Nueva Vizcaya");
supplier.setContactNumber("N/A");
if(this.supplierRepository.findById((long)1).isPresent()){
given(this.supplierRepository.findById((long)1).get()).willReturn(supplier);
}
mvc.perform(get("/supplier/1"))
.andExpect(status().isOk())
.andExpect(view().name("supplier"))
.andExpect(model().attributeExists("supplier"))
.andExpect(model().attribute("supplier", equalTo(supplier)));
}
但是当我运行它时,我得到了这个错误
org.springframework.web.util.NestedServletException: 请求 处理失败;嵌套异常是 org.thymeleaf.exceptions.TemplateProcessingException:期间出错 处理器的执行 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (模板:“供应商” - 第 16 行,第 25 列)
在我看来第 16 行是这样的
<input type="hidden" th:field="*{id}" />
我也从这些行中得到错误
<title th:text="${#strings.isEmpty(supplier.id) ? 'New Supplier' : 'Update Supplier '+supplier.id }"></title>
我认为这与供应商实体有关。 我做这个测试对吗?我可以做些什么来解决这些问题?
查了一下发现
if(this.supplierRepository.findById((long)1).isPresent()){
given(this.supplierRepository.findById((long)1).get()).willReturn(supplier);
}
自
以来没有返回做任何事情this.supplierRepository.findById((long)1).isPresent()
是假的。
如何在 given() 中使用 findById?
【问题讨论】:
-
我认为这与Spring data 2.0.0 findById有关。 if(this.supplierRepository.findById(1L).isPresent()){ given(this.supplierRepository.findById(1L).get()).willReturn(supplier); } 没有返回任何东西
标签: spring-boot spring-data thymeleaf spring-test spring-boot-test