Springboot 测试用例 --Test Junit

Spring boot 测试用例 –Test Junit

1.pom.xml中添加配置spring-boot-starter-test

    <!-- Spring Boot junit 测试依赖 -->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

2.提供测试类

/**方式一 (boot 1.4 之后)
 * 
 */
//@RunWith(SpringRunner.class)
//@SpringBootTest(classes = AppWebApplication.class)

/**方式二 (boot 1.4 之前)
 * 
 */

//junit 还提供了  @DataJpaTest,@JsonTest,@JdbcTest  (SpringBootTest 是此Demo)等测试用例   有兴趣的可以研究
//一个测试类单元测试的执行顺序为:
//
//@BeforeClass –> @Before –> @Test –> @After –> @AfterClass
//
//每一个测试方法的调用顺序为:
//
//@Before –> @Test –> @After

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = AppWebApplication.class)
@WebAppConfiguration
public class Test1Controller {



    @Autowired
    private RedisTemplate redisTemplate;

    @Test
    public void redisTest() {
        ValueOperations valOpt = redisTemplate.opsForValue();
        System.out.println("redis demo success"+(String) valOpt.get("number"));
    }

    @Test  //测试方法,在这里可以测试期望异常和超时时间
    public void redisTest2() {
        ValueOperations valOpt = redisTemplate.opsForValue();
        System.out.println("redis demo success"+(String) valOpt.get("number"));
    }

    @Before //初始化方法 每次执行 test 都会执行 before 和 after 
    public void beforeMethod() {
        System.out.println("junit demo success  --> beforeMethod !");
    }

    @After  //释放资源
    public void afterMethod() {
        System.out.println("junit demo success  --> afterMethod !");
    }

    @BeforeClass  //针对所有测试,只执行一次,且必须为static void
    public static void beforeClassMethod() {
        System.out.println("junit demo success  --> beforeClassMethod !");
    }

    @AfterClass  //针对所有测试,只执行一次,且必须为static void
    public static void afterClassMethod() {
        System.out.println("junit demo success  --> afterClassMethod !");
    }

    @Ignore //忽略的测试方法
    public static void ignoreMethod() {
        System.out.println("junit demo success  --> ignoreMethod !");
    }




}

3.联合 打包测试

/**
 * 
 * 
 * @Description : 联合 打包测试
 *  正常情况下我们写了5个测试类,我们需要一个一个执行。 
 *  打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,
 *  然后直接运行这个类就达到同时运行其他几个测试的目的
 *
 */
@RunWith(Suite.class) 
@SuiteClasses({TestController.class, Test1Controller.class}) 
public class TestUnitController {

}

4.junit 涉及相关使用

1.关于Assert类中的一些断言方法,都很简单,本文不再赘述。
2.junit 捕获异常输出
3.使用Junit测试HTTP的API接口
4.点击方法名称,则为方法级别单元测试,点击类名 则为类级别测试

猜你喜欢

转载自blog.csdn.net/qing_mei_xiu/article/details/79745936
今日推荐