java - 如何防止 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"));
}
解决方案
推荐阅读
- c# - 无法获取 .net core 3.0 单个文件“/p:PublishSingleFile=true”的原始可执行路径
- python - Seaborn 散点图图例显示真实值和标准化连续颜色
- telegram - 是否应该为每个页面创建即时视图?
- ruby-on-rails - 用户使用电话号码注册时的 Rails 两因素身份验证
- javascript - 有没有一种在 Angular 7 中嵌入 iframe 的安全方法?
- c# - WCF DiscoverClient.FindAsync 抛出 SocketException
- scheduling - 如何在 CPLEX 的调度问题中添加新的约束?
- html - 分割 html 页面以填充所有窗口,顶部面板具有必要的最小高度,左侧面板和右侧面板具有固定宽度
- c# - 无法将类型“System.Web.Http.Results.BadRequestErrorMessageResult”隐式转换为“System.Net.Http.HttpResponseMessage”
- javascript - react.js 状态如何工作?