SpringBoot 使用 Junit

一、Spring Boot使用Junit步骤

1). 加入Maven的依赖:

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

 

2). 编写测试service:

新建com.spencer.service.HelloService 提供测试方法:

package com.spencer.service;

 

import org.springframework.stereotype.Service;

 

@Service

publicclass HelloService {

 

    public String sayHello(){

       return "hello!";

    }

}

 

3). 编写测试类:

src/test/Java下编写测试类:com.spencer.test.HelloServiceTest:

package com.spencer.test;

 

import javax.annotation.Resource;

 

import org.junit.Assert;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import org.springframework.boot.test.context.SpringBootTest; 

import com.spencer.App;

import com.spencer.service.HelloService;

 

SpringJUnit支持,由此引入Spring-Test框架支持!

@RunWith(SpringJUnit4ClassRunner.class)

 指定我们SpringBoot工程的Application启动类

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE, classes = App.class)

public class HelloServiceTest {

    @Resource

    private HelloService helloService;

    @Test

    publicvoid testGetName(){

       Assert.assertEquals("hello",helloService.getName());

    }

}

这时候就可以进行测试了,右键—Run As – Junit Test

 

 

二、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测试,不涉及Spring Web项目,你可以省略@RunWith注解,这样系统会自动使用默认Runner来运行你的代码。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值