Spring Boot 2.1 / 2.2测试-如何在不为其他所有功能创建bean的情况下测试单个控制器?

时间:2019-11-19 22:45:21

标签: spring spring-boot testing kotlin

在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. 要创建(尝试)Irelevant Bean:kotlin.UninitializedPropertyAccessException: lateinit property <property> has not been initialized-来自@ConfigurationProperties类。

以及其他一些对我来说毫无意义的东西(在2.2版本中,我@DataJpaTest@SpringBootTest都不能在一起)。

有人知道如何正确更新这些单元测试吗?

1 个答案:

答案 0 :(得分:0)

您可以使用切片测试@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实例,而不必自己连接。