详细的Spring Boot Junit单元测试

电脑杂谈  发布时间:2020-05-26 00:06:35  来源:网络整理

junit测试失败_junit 打包排除测试类_junit测试类

Junit的旧技术现在被拿出来,并说,在某种程度上,这并不是为了说明什么,而是要说明其在项目中的重要性.

根据我的感受和经验,在项目中编写Junit用例以根据标准覆盖大多数业务代码的时间不应超过一半.

不久前我刚刚写了一些有关SpringBoot的帖子,现在我只是把Junit带出去,从几个方面进行讨论,这也是一些新手的参考.

所以让我们简短地谈谈为什么我们需要编写测试用例

1. 它可以避免遗漏测试点,从而更好地进行测试,可以提高测试效率.

2. 在打包项目之前junit 打包排除测试类,它可以自动进行测试并可以进行测试和验证

3. 您会发现由于及时修改代码而导致的新问题并及时解决

然后本文从以下几点说明如何使用Junit. Junit4比3方便得多. 您可以了解详细信息. 主要原因是版本4不再需要方法命名格式,也不再需要继承TestCase两者都是基于注释的.

junit 打包排除测试类_junit测试失败_junit测试类

1,如何在SpringBoot Web项目中使用Junit

创建一个普通的Java类,不再需要在Junit4中继承TestCase类.

因为我们是一个Web项目,所以在创建的Java类中添加一条注释:

@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持! 
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。

接下来,您可以编写测试方法. 可以使用@Test批注标记测试方法.

在此类中,我们可以直接@Autowired像往常一样注入要测试的类的实例.

这是完整的代码:

package org.springboot.sample;
import static org.junit.Assert.assertArrayEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springboot.sample.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
/**
 *
 * @author  单红宇(365384722)
 * @create  2016年2月23日
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
@WebAppConfiguration
public class StudentTest {
  @Autowired
  private StudentService studentService;
  @Test
  public void likeName() {
    assertArrayEquals(
        new Object[]{
            studentService.likeName("小明2").size() > 0,
            studentService.likeName("坏").size() > 0,
            studentService.likeName("莉莉").size() > 0
          }, 
        new Object[]{
            true,
            false,
            true
          }
    );
//   assertTrue(studentService.likeName("小明2").size() > 0);
  }
}

junit测试类_junit测试失败_junit 打包排除测试类

接下来,您需要添加无数的测试类并编写无数的测试方法,以确保我们开发的程序的有效性.

2. Junit基本注释简介

//在所有测试方法前执行一次,一般在其中写上整体初始化的代码 
@BeforeClass
//在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码 
@AfterClass
//在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据) 
@Before
//在每个测试方法后执行,在方法执行完成后要做的事情 
@After
// 测试方法执行超过1000毫秒后算超时,测试将失败 
@Test(timeout = 1000)
// 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败 
@Test(expected = Exception.class)
// 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类 
@Ignore(“not ready yet”) 
@Test
@RunWith 

JUnit中有许多运行器. 他们负责调用您的测试代码. 每个亚军都有自己的特殊功能. 您需要根据需要选择其他运行程序以运行测试代码.

如果我们只是在不涉及Spring Web项目的情况下进行普通Java测试,则可以省略@RunWith注释,以便系统将自动使用默认的Runner运行您的代码.

3. 参数测试

Junit为我们提供的参数化测试需要使用@RunWith(Parameterized.class)

但是,由于Junit使用@RunWith指定Runner,因此在更多情况下,我们需要使用@RunWith(SpringJUnit4ClassRunner.class)来测试我们的Spring工程方法,因此我们使用assertArrayEquals来测试该方法可以的多种可能性.

junit测试类_junit 打包排除测试类_junit测试失败

这是参数化测试的一个简单示例:

package org.springboot.sample;
import static org.junit.Assert.assertTrue;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class ParameterTest {
  private String name;
  private boolean result;
  /**
   * 该构造方法的参数与下面@Parameters注解的方法中的Object数组中值的顺序对应
   * @param name
   * @param result
   */
  public ParameterTest(String name, boolean result) {
    super();
    this.name = name;
    this.result = result;
  }
  @Test
  public void test() {
    assertTrue(name.contains("С") == result);
  }
  /**
   * 该方法返回Collection
   *
   * @return
   * @author SHANHY
   * @create 2016年2月26日
   */
  @Parameters
  public static Collection<> data(){
    // Object 数组中值的顺序注意要和上面的构造方法ParameterTest的参数对应
    return Arrays.asList(new Object[][]{
      {"小明2", true},
      {"坏", false},
      {"莉莉", false},
    });
  }
}

4. 包装测试

在正常情况下,我们编写了5个测试类,我们需要一个一个地执行.

打包测试是添加一个新类,然后配置我们一起编写的其他测试类,然后直接运行该类,以达到同时运行其他几个测试的目的.

代码如下:

@RunWith(Suite.class) 
@SuiteClasses({ATest.class, BTest.class, CTest.class}) 
public class ABCSuite {
  // 类中不需要编写代码
} 

5. 使用Junit测试HTTP API接口

junit测试失败_junit 打包排除测试类_junit测试类

我们可以直接使用它来测试Rest API. 如果内部单元测试要求不是很严格,则我们保证外部API会经过全面测试,因为该API会调用许多内部方法,因此将其视为集成测试.

这是一个简单的例子:

package org.springboot.sample;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.hamcrest.Matchers;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
/**
 *
 * @author  单红宇(365384722)
 * @create  2016年2月23日
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest {
  private String dateReg;
  private Pattern pattern;
  private RestTemplate template = new TestRestTemplate();
  @Value("${local.server.port}")// 注入端口号
  private int port;
  @Test
  public void test3(){
    String url = "http://localhost:"+port+"/myspringboot/hello/info";
    MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>(); 
    map.add("name", "Tom"); 
    map.add("name1", "Lily");
    String result = template.postForObject(url, map, String.class);
    System.out.println(result);
    assertNotNull(result);
    assertThat(result, Matchers.containsString("Tom"));
  }
}

6. 捕获输出

在指定的方法开始执行后,使用OutputCapture捕获所有输出,包括System.out输出和Log log.

OutputCapture需要用@Rule注释,实例化的对象需要用public装饰,如以下代码所示:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest {
  @Value("${local.server.port}")// 注入端口号
  private int port;
  private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
  @Rule
  // 这里注意,使用@Rule注解必须要用public
  public OutputCapture capture = new OutputCapture();
  @Test
  public void test4(){
    System.out.println("HelloWorld");
    logger.info("logo日志也会被capture捕获测试输出");
    assertThat(capture.toString(), Matchers.containsString("World"));
  }
}

Assert类中的Assert方法非常简单,在本文中将不再重复.

但是,在新版本的Junit中,assertEquals方法已被弃用. 建议我们使用assertArrayEquals,它旨在允许我们在测试方法时为多个可能性传递多个参数.

以上是本文的全部内容junit 打包排除测试类,希望对大家的学习有所帮助,并希望每个人都支持此脚本.


本文来自电脑杂谈,转载请注明本文网址:
https://www.pc-fly.com/a/ruanjian/article-222197-1.html

    相关阅读
      发表评论  请自觉遵守互联网相关的政策法规,严禁发布、暴力、反动的言论

      • 李兼
        李兼

        英雄所见略同

      • 王台卿
        王台卿

        如果他们胆敢撞击或者攻击我们的渔船

      热点图片
      拼命载入中...