本文主要是介绍【Spring boot】编写代码及测试用例入门之 Hello Spring boot _踩坑记,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
先贴下目录:
这是我从 start.spring.io
里下载的依赖Web的模板
// DemoApplication.java
package com.abloume.springboot.blog.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
// 这里有一个坑,没有注册扫描器,下面分析时会有说明
public class DemoApplication {public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);}
}
// HelloController.java
package com.abloume.springboot.blog.controller;import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;@RestController
// 使用 @RestController 相当于 @Controller 和 @RequestBody
public class HelloController {@RequestMapping("/hello")public String hello() {return "Hello Spring boot!";}
}
// DemoApplicationTests
package com.abloume.springboot.blog.demo;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;@RunWith(SpringRunner.class)
@SpringBootTest
public class DemoApplicationTests {@Testpublic void contextLoads() {}}
// HelloControllerTest
package com.abloume.springboot.blog.controller;import com.abloume.springboot.blog.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;import static org.hamcrest.core.IsEqual.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;@RunWith(SpringRunner.class)
@SpringBootTest // 这里有一个配置坑
@AutoConfigureMockMvc
public class HelloControllerTest {@Autowiredprivate MockMvc mockMvc;@Testpublic void testHello() throws Exception {mockMvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk()).andExpect(content().string(equalTo("Hello Spring boot!")));};
};
下面贴上自己的报错图及解决方案:
解决方案:
// 这里需要指定它的启动类
@SpringBootTest(classes = DemoApplication.class)
报错404说明路径错误匹配不到,但前后路径是对应的都是 "/hello"
;
再仔细看 HelloController.java
发现未被使用
解决方案:需要在启动类中添加扫描注解即可
浏览器上运行看一下,Ok~
这篇关于【Spring boot】编写代码及测试用例入门之 Hello Spring boot _踩坑记的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!