【问题标题】:Thymeleaf errors when doing mvc tests进行 mvc 测试时出现 Thymeleaf 错误
【发布时间】: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-boot spring-data thymeleaf spring-test spring-boot-test


【解决方案1】:

已经通过修改解决了

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 2011-01-25
    相关资源
    最近更新 更多