java - 具有真实服务实现的 WebMvcTest
问题描述
如何在 Spring Boot 中创建“准”MVC 集成测试。我想使用我真正的服务实现,但我做不到。我怎样才能注入真正的实现而不是模拟。我的课看起来像这样
@Controller
@RequiredArgsConstructor
public class DashboardController {
private final RolesManagerService rolesManagerService;
private final ServletRequestManagerService servletRequestManagerService;
@GetMapping({"/", "/dashboard"})
public String index(Model model, HttpServletRequest httpServletRequest) {
model.addAttribute("canAddNewOrder", rolesManagerService.canRoleAccessApplicationPart(servletRequestManagerService.getRole(httpServletRequest), ApplicationPart.CREATE_NEW_ORDER));
model.addAttribute("var", "test");
return "dashboard";
}
}
和测试
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = DashboardController.class)
@AutoConfigureMockMvc
class IndexControllerTest {
@Autowired
private MockMvc mockMvc;
@MockBean
private UserDetailsService userDetailsService;
@MockBean
RolesManagerService rolesManagerService;
@MockBean
private ServletRequestManagerService servletRequestManagerService;
@Test
void testDashboard() throws Exception {
mockMvc.perform(get("/dashboard").with(user("admin").password("pass").roles("USER","ADMIN")))
.andExpect(status().isOk())
.andExpect(view().name("dashboard"))
.andExpect(xpath("//a").nodeCount(1))
.andExpect(model().attributeExists("canAddNewOrder"))
.andExpect(model().size(2))
.andExpect(model().attribute("var", equalTo("test")))
.andExpect(model().attribute("canAddNewOrder", equalTo(false)))
.andDo(print());
}
}
解决方案
通常 WebMvcTest 不会创建一个包含所有组件(服务等)注入的完整 Spring 上下文,而只会创建您定义的控制器。要么使用完整的 SpringBootTest,要么在 WebMvcTest 类中添加类似的内容:
@TestConfiguration
static class AdditionalTestConfig {
@Bean
public RolesManagerService getService() {
return new RolesManagerService();
}
}
推荐阅读
- python - 用于构建 python 应用程序的 Setup.py 和 Docker 分层
- eclipse - JavaFX FXML:如何将自制 fxml 的新实例创建到 VBox
- firebase - 在 Flutter StateNotifier + Riverpod 架构中初始化未来数据
- vuelidate - 如何验证至少一个输入已填充?
- c# - 如何添加变换算法(“envelope-signature”)
- vue.js - vue-i18n this.$tc 不是函数
- python - 在函数中使用未经授权的参数名称
- r - 在 R 中设置数据框
- python - UnicodeDecodeError:“utf-8”编解码器无法解码位置 125 中的字节 0xb2:无效的起始字节
- entity-framework - .NET Core 3.1 - 控制台应用程序 + EF - .Include 不加载数据