在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之后,我遇到各种随机错误,例如:
java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(value=user, userDetailsServiceBeanName=, setupBefore=TEST_METHOD)
kotlin.UninitializedPropertyAccessException: lateinit property <property> has not been initialized
-来自@ConfigurationProperties
类。以及其他一些对我来说毫无意义的东西(在2.2版本中,我@DataJpaTest
和@SpringBootTest
都不能在一起)。
有人知道如何正确更新这些单元测试吗?
答案 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
实例,而不必自己连接。