如何为Spring Boot Controller端点编写单元测试

如何为Spring Boot Controller端点编写单元测试

问题描述:

我有一个示例Spring Boot应用程序,其中包含以下内容

I have a sample Spring Boot app with the following

引导主类

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

控制器

@RestController
@EnableAutoConfiguration
public class HelloWorld {
    @RequestMapping("/")
    String gethelloWorld() {
        return "Hello World!";
    }

}

写一个最简单的方法是什么?控制器的单元测试?我尝试了以下但它抱怨无法自动装载WebApplicationContext

What's the easiest way to write a unit test for the controller? I tried the following but it complains about failing to autowire WebApplicationContext

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = DemoApplication.class)
public class DemoApplicationTests {

    final String BASE_URL = "http://localhost:8080/";

    @Autowired
    private WebApplicationContext wac;

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception{

         this.mockMvc.perform(get("/")
                 .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                 .andExpect(status().isOk())
                 .andExpect(content().contentType("application/json"));
    }

    @Test
    public void contextLoads() {
    }

}


Spring MVC提供 standaloneSetup ,支持测试相对简单的控制器,没有需要上下文。

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.


通过注册一个或多个@ Controller的实例和
以编程方式配置Spring MVC基础架构来构建MockMvc。这允许
完全控制控制器的实例化和初始化,
及其依赖项,类似于普通单元测试,同时还可以使
一次测试一个控制器。

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

您的控制器的示例测试可以是简单的事情

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json"));

    }
}