首页 > 解决方案 > 如何防止 Thymeleaf 模板引擎读取路径 URL 获取映射作为 Spring Boot 中的模板引擎名称

问题描述

我有一个控制器获取映射,它读取路径变量以从存储库返回对象,并使用 Thymeleaf 返回模板引擎名称以显示它,它在带有邮递员和浏览器的 localhost 中运行良好:

@Controller
public class InvoiceFormController {

  @Autowired
  InvoiceDetailRepository invoiceDetailRepository;

  @Autowired
  InvoiceService invoiceService;

  @GetMapping("/supermarket/invoice/{id}")
  public String getInvoiceView(@PathVariable("id") UUID id, Model model) {
    InvoiceDetail invoiceDetail = invoiceDetailRepository.getInvoiceDetailById(id);
    if(invoiceDetail == null) {
      return invoiceService.showError(model);
    }
    return invoiceService.showDetail(invoiceDetail, model);
  }
}

这是服务:

@Service
public class InvoiceService {

    public Spring showDetail(InvoiceDetail invoiceDetail, Model model) {
      model.addAttribute("invoiceDetail", invoiceDetail);
      return "invoicePage";
    }

    public Spring showError(Model model) {
      model.addAttribute("error", "not found");
      return "errorPage";
    }
}

但是,当我创建单元测试时,它总是出错,因为路径 url 获取映射总是被 Spring Boot 读取为模板引擎名称:

ERROR org.thymeleaf.TemplateEngine -[THYMELEAF][main] Exception processing template "supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067": Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [supermarket/invoice/d5afd278-db7c-4482-b992-c7440b522067], template might not exist or might not be accessible by any of the configured Template Resolvers

单元测试是这样的:

@WebMvcTest(InvoiceFormController.class)
class InvoiceFormControllerTest {

  @Autowired
  private MockMvc mockMvc;
  @MockBean
  InvoiceDetailRepository invoiceDetailRepository;
  @MockBean
  InvoiceService invoiceService;
  @Mock
  Model model;

  @Test
  void testViewSuccess() throws Exception {

    InvoiceDetail invoiceDetail = InvoiceDetail.builder().id(UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068").build();

    UUID id = UUID.fromString("d5afd278-db7c-4482-b992-c7440b522068");

    Mockito.when(invoiceDetailRepository.getInvoiceDetailById(id))
            .thenReturn(invoiceDetail);

    Mockito.when(invoiceService.showDetail(invoiceDetail, model))
            .thenReturn("invoicePage");

    mockMvc.perform(MockMvcRequestBuilders.get("/supermarket/invoice/"+"d5afd278-db7c-4482-b992-c7440b522068"))
            .andExpect(MockMvcResultMatchers.status().isOk());
            .andExpect(MockMvcResultMatchers.view().name("invoicePage"));
}

标签: javaspring-bootthymeleaf

解决方案


推荐阅读