前言:今天开始学习SpringBoot,顺便记录一点自己的收获。
1、创建一个SpringBoot工程:
这样,一个SpringBoot工程就创建好了。
2、创建一个controller类:
@RestController public class HelloController { @RequestMapping("/woo") public String hello(){ return "woo~ this is spring boot."; } }
3、编写一个引导类:
@SpringBootApplication public class SpringBootDay1Application { public static void main(String[] args) { SpringApplication.run(SpringBootDay1Application.class, args); } }
通过引导类(即,SpringBoot项目的入口)将其运行起来:
4、编写单元测试:
单元测试在开发的过程中还是很重要的,能让我们及时发现错误并纠正,避免面对庞大的代码和不知在哪的报错。
@RunWith(SpringRunner.class) @SpringBootTest public class HelloControllerTest { @Autowired HelloController helloController; /** * 验证HelloController的输出结果与"woo~ this is spring boot."是否一致 */ @Test public void should_equals_hello(){ String result = helloController.hello(); Assert.assertEquals("woo~ this is spring boot.",result); } /** * 验证写错时能否发现 */ @Test public void should_not_equals_hello(){ String result = helloController.hello(); Assert.assertNotEquals("hello world",result); } }
运行结果:
当我们将上下两个测试类互换检验的句子时:
@RunWith(SpringRunner.class) @SpringBootTest public class HelloControllerTest { @Autowired HelloController helloController; /** * 验证HelloController的输出结果与"woo~ this is spring boot."是否一致 */ @Test public void should_equals_hello(){ String result = helloController.hello(); Assert.assertEquals("woo~",result); } /** * 验证写错时能否发现 */ @Test public void should_not_equals_hello(){ String result = helloController.hello(); Assert.assertNotEquals("woo~ this is spring boot.",result); } }
运行结果:
因为代码很少,所以单元测试的效果看起来并不明显。但它的确可以让我们及时地发现错误。同时,因为单元测试建在test包下,所以代码不会乱糟糟的,能很清楚地发现问题。