我正在尝试测试我的控制器,该控制器采用更新供应商的形式
//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:Request 处理失败;嵌套异常是 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()
是假的。
如何在给定的()中使用findById?
答案 0 :(得分:0)
已经通过更改
解决了这个问题if(this.supplierRepository.findById((long)1).isPresent()){
given(this.supplierRepository.findById((long)1).get()).willReturn(supplier);
}
到
given(this.supplierRepository.findById(1L)).willReturn(Optional.of(supplier));
问题是第一个存根返回null