首页 > 解决方案 > Spring Boot 2.1/2.2 测试 - 如何在不为其他所有内容创建 bean 的情况下测试单个控制器?

问题描述

在 Spring Boot 2.0 之前,我有类似的东西:

@RunWith(SpringRunner::class)
@DataJpaTest
@AutoConfigureMockMvc
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("unit-test")
@SpringBootTest
@WithUserDetails
class MyControllerTest {

    @InjectMocks
    lateinit var myController: MyController

    lateinit var mvc: MockMvc

    @Before
    fun setup() {
        mvc = MockMvcBuilders.standaloneSetup(myController).build()
    }
...

但是在尝试升级到 Spring Boot 2.1 之后,我得到了各种随机错误,例如:

  1. WithUserDetails 不起作用:java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(value=user, userDetailsServiceBeanName=, setupBefore=TEST_METHOD)
  2. (尝试)创建不相关的 bean:kotlin.UninitializedPropertyAccessException: lateinit property <property> has not been initialized- 这是来自一个@ConfigurationProperties类。

以及其他一些对我来说没有意义的东西(在 2.2 中,我也不能同时拥有两者@DataJpaTest@SpringBootTest

有没有人知道我需要做什么才能正确更新这些单元测试?

标签: springspring-boottestingkotlin

解决方案


您可以使用切片测试@WebMvcTest或完整集成测试@SpringBootTest。因此,将它们一起使用是没有意义的。在您的情况下,您想测试一个控制器,然后使用@WebMvcTest并模拟依赖项。

@RunWith(SpringRunner::class)
@WebMvcTest(MyController.class)
@WithUserDetails
class MyControllerTest {

    @Autowired
    lateinit var myController: MyController

    @Autowired
    lateinit var mvc: MockMvc


    @MockBean
    var myService: MyServiceForController

用于@MockBean模拟控制器的服务依赖项并在其上注册行为。您现在还可以简单地连接控制器和预设置MockMvc实例,而不是自己连接。


推荐阅读