关于SpringBoot与单元测试

前言:今天开始学习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包下,所以代码不会乱糟糟的,能很清楚地发现问题。

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值