我想在不使用@SpringBootTest注解的情况下测试一个控制器。

huangapple go评论81阅读模式
英文:

I want to test a controller without using @SpringBootTest

问题

我有以下的测试类:

@SpringBootTest
public class ChoreControllerTest
{
    @Autowired 
    private ChoreController controller;

    @Test
    public void throwOnMissingChore()
    {
        assertThrows(ChoreNotFoundException.class, () -> this.controller.getChore(0L));
    }
}

Spring Boot 启动大约需要 5 秒钟,以便测试可以运行。我想缩短这个时间,但如果我只是移除 @SpringBootTest 注解,我会得到一个 NPE(NullPointerException)。

有没有办法使这个控制器测试变得更加轻量,还是我必须忍受启动时间?我特别担心如果我想测试多个控制器,我的测试时间会怎么样……

英文:

I have the following test 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. I want to reduce this time, but if I just remove the @SpringBootTest annotaton, I just get a NPE.

Is there a way to make this controller test more lightweight, or am I stuck with the startup time? I'm especially worried about what will happen to my test times if I ever want to test more than one controller....

答案1

得分: 4

@SpringBootTest注解会为您创建一个Spring上下文,因此启动需要一些时间。这个注解主要用于需要Spring上下文的集成测试。这里有一些优化集成测试的建议。
如果您移除这个注解,ChoreController将无法自动注入(没有可用的上下文),从而导致NullpointerException。
根据您的需求,您可以使用Mockito等模拟库来注入模拟对象,比如控制器类需要的服务,并在没有@SpringBootTest的情况下运行测试。

您可能想查看这篇文章以正确设置这些模拟对象。

英文:

The @SpringBootTest annotations create a Spring Context for you therefore it takes a while to start up. This annotation is mostly used for integration tests where a Spring context is required. 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.
Depending on your needs you can just use a Mocking library like Mockito to inject mocks e.g. 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.

huangapple
  • 本文由 发表于 2020年5月30日 23:07:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/62104370.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定