springboot项目编写单元测试_如何为Spring Boot Controller端点编写单元测试 - Go语言中文社区

springboot项目编写单元测试_如何为Spring Boot Controller端点编写单元测试


I have a sample Spring Boot app with the following

Boot main class

@SpringBootApplication

public class DemoApplication {

public static void main(String[] args) {

SpringApplication.run(DemoApplication.class, args);

}

Controller

@RestController

@EnableAutoConfiguration

public class HelloWorld {

@RequestMapping("/")

String gethelloWorld() {

return "Hello World!";

}

}

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 offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

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"));

}

}

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/weixin_39643679/article/details/111766282
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-06-26 21:36:17
  • 阅读 ( 646 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢