Spring Boot 2.1/2.2 测试 - 如何在不为其他一切创建 bean 的情况下测试单个 Controller ?

标签 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. 正在(尝试)创建不相关的 bean:kotlin.UninitializedPropertyAccessException: lateinit property <property> has not been initialized - 这是来自 @ConfigurationProperties类。

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

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

最佳答案

您可以使用切片测试 @WebMvcTest 或使用 @SpringBootTest 的完整集成测试。因此将它们一起使用是没有意义的。在您的情况下,您想测试一个 Controller ,然后使用 @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 模拟 Controller 的服务依赖并在其上注册行为。您现在还可以简单地连接 Controller 和预设置 MockMvc 实例,而不是自己连接。

关于Spring Boot 2.1/2.2 测试 - 如何在不为其他一切创建 bean 的情况下测试单个 Controller ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58943998/

相关文章:

java - 为什么 html 页面没有显示在 thymeleaf 中?

maven - 无法解析 spring-web-reactive 的依赖项

java - Camel : integration tests of asynchronous routes

java - 奇怪的java.io.NotSerializedException : org. springframework.dao.support.PersistenceExceptionTranslationInterceptor

java - 如何在运行时切换 Spring 配置文件

spring - Spring中的JUnit测试-覆盖和忽略来自应用程序其他配置类的bean

ruby - 如何使用 Capybara/Ruby 测试与页面上相同正则表达式匹配的多个字符串实例

java - 如何在 Spring Boot 应用程序中的其他类中 Autowiring bean?

javax.sql.DataSource BeanCurrentlyInCreationException(循环引用?)

exception - MiniDFSCluster 给出 ioexception