Spring Boot进阶之Web 2-7

视频教程地址

https://www.imooc.com/video/14342

单元测试

目录

  • 测试service
  • 测试API

测试service

  • 测试代码如下
package com.imooc;

import com.imooc.domain.Girl;
import com.imooc.service.GirlService;
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;

/**
 * @author wdh
 */
@RunWith(SpringRunner.class)
//由于低层使用Junit测试需要加上如下注解
@SpringBootTest
public class GirlServiceTest {

    //注入需要测试的service
    @Autowired
    private GirlService girlService;

    //测试方法上需要加上@Test注解
    @Test
    public void findOneTest() {
        Girl girl = girlService.findOne(73);
        //使用断言
        Assert.assertEquals(new Integer(13), girl.getAge());
    }
}

如何运行测试用例
在这里插入图片描述

当然可以利用idea更方便的创建测试方法

在这里插入图片描述

想测试那个方法就勾选哪个在这里插入图片描述
生成的代码

package com.imooc.service;

import org.junit.Test;

/**
 * @author wdh
 */
public class GirlServiceTest {
    @Test
    public void findOne() throws Exception {

    }

}

测试API

在这里插入代码片package com.imooc.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

/**
 * API测试
 * @author wdh
 */
@RunWith(SpringRunner.class)
@SpringBootTest
//需要使用MockMvc所以要加上这个注解
@AutoConfigureMockMvc
public class GirlControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void girlList() throws Exception {
        //对/girls地址进行get方法调用andExpect后面加上期望返回的结果andExpect期望返回的Exception
        mvc.perform(MockMvcRequestBuilders.get("/girls"))
                .andExpect(MockMvcResultMatchers.status().isOk())
        .andExpect(MockMvcResultMatchers.content().string("abc"));
    }

}

当测试用例过多的时候(mvn)
可以再他会在打包的时候自动运行单元测试。

mvn clean package

打包的时候跳过单元测试

mvn clean package -Dmaven.test.skip=true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值