Springboot_13_单元测试

http://412887952-qq-com.iteye.com/blog/2317832-Junit1.4版本

添加依赖

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
  </dependency>

测试Service

@Service
public class StudentService{
    @Resource
    private StudentDao studentDao;

    public String junitTest(){
        return "hello";
    }
}

测试

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.tutorial.springboot.AppStart;
import com.tutorial.springboot.service.StudentService;

//SpringJUnit支持,由此引入Spring-Test框架支持
@RunWith(SpringJUnit4ClassRunner.class)
//指定我们SpringBoot工程的Application启动类
@SpringApplicationConfiguration(classes = AppStart.class)
//1.4.0已经被标注过时,需要替换为@SpringbootTest注解
//由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration
@WebAppConfiguration
public class SpringBootTest{
    @Resource
    private StudentService studentService;

    @Test
    public void testGetName(){
           Assert.assertEquals("hello",studentService.junitTest());
    }
}

Junit基本注解介绍

//在所有测试方法前执行一次,一般在其中写上整体初始化的代码 @BeforeClass
//在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码 @AfterClass
//在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据) @Before
//在每个测试方法后执行,在方法执行完成后要做的事情 @After
// 测试方法执行超过1000毫秒后算超时,测试将失败 @Test(timeout = 1000)
// 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败 @Test(expected = Exception.class)
// 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类 @Ignore(“not ready yet”) @Test
@RunWith 在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。 如果我们只是简单的做普通Java测试,不涉及SpringWeb项目,你可以省略@RunWith注解,这样系统会自动使用默认Runner来运行你的代码。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 使用SpringMVC来实现一组对User对象操作的RESTful API,配合注释详细说明在Spring MVC...
    perfect_jimmy阅读 3,570评论 0 0
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,269评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,224评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 177,123评论 25 709
  • 木子李 遇见柠檬 柠檬,没有棠梨胭脂色,没有荞麦白雪香 但是,它是不一样的黄,不一样的青 是黄得耀眼,青得乐观 经...
    芷木槿阅读 1,319评论 0 1

友情链接更多精彩内容