spring - 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 之后,我得到了各种随机错误,例如:
- WithUserDetails 不起作用:
java.lang.IllegalStateException: Unable to create SecurityContext using @org.springframework.security.test.context.support.WithUserDetails(value=user, userDetailsServiceBeanName=, setupBefore=TEST_METHOD)
- (尝试)创建不相关的 bean:
kotlin.UninitializedPropertyAccessException: lateinit property <property> has not been initialized
- 这是来自一个@ConfigurationProperties
类。
以及其他一些对我来说没有意义的东西(在 2.2 中,我也不能同时拥有两者@DataJpaTest
)@SpringBootTest
。
有没有人知道我需要做什么才能正确更新这些单元测试?
解决方案
您可以使用切片测试@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
实例,而不是自己连接。
推荐阅读
- laravel - 如何将数组请求保存在数据库中
- java - java stream api - 更改流
- >> 配对
- , 列表>
- html - 带有 iframe 的 Html 代码在 Mozilla 和 Edge 中不起作用
- mysql - DATEDIFF 在 BEFORE INSERT 触发器中返回 NULL
- tensorboard - 修改 tf.estimator.Estimator 如何为 Tensorboard 创建摘要
- graph - neo4j 删除和创建节点和链接
- c# - 在 Visual Studio 中录制 Web 负载测试项目
- sql-server - 创建 MS SQL 存储过程时出错
- javascript - 在Angular 4中的第n个孩子内创建一个div元素
- python-3.x - 区分调用唯一参数和在互斥组中使用 argparse 提供字符串