[英]I want to test a controller without using @SpringBootTest
I have the following test class:我有以下测试 class:
@SpringBootTest
public class ChoreControllerTest
{
@Autowired
private ChoreController controller;
@Test
public void throwOnMissingChore()
{
assertThrows(ChoreNotFoundException.class, () -> this.controller.getChore(0L));
}
}
It takes about 5 seconds for Spring Boot to start up so the test can run. Spring Boot 启动大约需要 5 秒,这样才能运行测试。 I want to reduce this time, but if I just remove the
@SpringBootTest
annotaton, I just get a NPE.我想减少这个时间,但如果我只是删除
@SpringBootTest
注释,我只会得到一个 NPE。
Is there a way to make this controller test more lightweight, or am I stuck with the startup time?有没有办法让这个 controller 测试更轻量级,还是我坚持启动时间? I'm especially worried about what will happen to my test times if I ever want to test more than one controller....
我特别担心如果我想测试多个 controller,我的测试时间会发生什么......
The @SpringBootTest
annotations create a Spring Context for you therefore it takes a while to start up. @SpringBootTest
注释会为您创建一个 Spring 上下文,因此启动需要一段时间。 This annotation is mostly used for integration tests where a Spring context is required.此注释主要用于需要 Spring 上下文的集成测试。 Here are a few tips for optimizing integration tests.
这里有一些优化集成测试的技巧。 If you remove the annotation the ChoreController cannot be autowired (no context available) which results in a NullpointerException.
如果删除注释,则无法自动装配 ChoreController(没有可用的上下文),这会导致 NullpointerException。
Depending on your needs you can just use a Mocking library like Mockito to inject mocks eg services that your controller class needs and run the test without the @SpringBootTest
. Depending on your needs you can just use a Mocking library like Mockito to inject mocks eg services that your controller class needs and run the test without the
@SpringBootTest
.
You might want to take a look at this article for setting up those mocks properly.您可能想看看这篇文章以正确设置这些模拟。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.