【系统学习SpringBoot】初见单元测试

来源:互联网 发布:mac 输入法切换 编辑:程序博客网 时间:2024/06/05 19:11

Junit单元测试是开发非本地程序最好的测试方式。
【非本地程序】(自己比习惯这样分,不知道有不有官方这样叫)本地主要指PC端,也就是开发者的工作空间就算是本地。非本地程序例如:tomcat上运行的项目(jar/war),或者Android平台上运行的APP,,这就算是非本地程序了。对于非本地程序想很方便的测试时很麻烦的,需要把项目打包,放在服务器上跑,然后打开指定的url,访问…….(再说又要挨打了(●’◡’●))
总之很麻烦。时间全用到部署上了,效率太低了。

SpringBoot作为新兴其的一个框架对于单元测测试可谓是“自带的”用起来相当方便



新建项目时就带有测试的目录:

这里写图片描述



继上篇《SpringBoot新建HelloWorld工程(IDEA)》
对其中【HelloController】中的hello()方法进行测试,测试代码如下:

package xatu.zsl;import org.junit.Assert;import org.junit.Test;import org.junit.runner.RunWith;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.test.context.junit4.SpringRunner;import xatu.zsl.controller.HelloController;@RunWith(SpringRunner.class)@SpringBootTestpublic class StudyBootDemoApplicationTests {    @Autowired  //通过spring容器自动注入    private HelloController controller;    @Test    public void TestHelloWorld() {        Assert.assertEquals("Hello SpringBoot!", controller.hello());    }}

运行截图如下:
这里写图片描述



很方便,,方法

【注意】和spring单元测试一样,传入的对象可以通过注入的方式获取

    @Autowired  //通过spring容器自动注入    private HelloController controller;
原创粉丝点击