Spring Boot Junit单元测试

梦里梦外; 2022-07-16 09:58 286阅读 0赞

摘要: Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性。 凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分业务代码的,应该不会超过一半。 刚好前段时间写了一些关于SpringBoot的帖子,正好现在把Junit再拿出来从几个方面再说一…

Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性。
凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分业务代码的,应该不会超过一半。

刚好前段时间写了一些关于SpringBoot的帖子,正好现在把Junit再拿出来从几个方面再说一下,也算是给一些新手参考了。

那么先简单说一下为什么要写测试用例

  1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率
  2. 可以自动测试,可以在项目打包前进行测试校验
  3. 可以及时发现因为修改代码导致新的问题的出现,并及时解决

那么本文从以下几点来说明怎么使用Junit,Junit4比3要方便很多,细节大家可以自己了解下,主要就是版本4中对方法命名格式不再有要求,不再需要继承TestCase,一切都基于注解实现。

1、SpringBoot Web项目中中如何使用Junit

创建一个普通的Java类,在Junit4中不再需要继承TestCase类了。
因为我们是Web项目,所以在创建的Java类中添加注解:

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

接下来就可以编写测试方法了,测试方法使用@Test注解标注即可。
在该类中我们可以像平常开发一样,直接@Autowired来注入我们要测试的类实例。
下面是完整代码:

  1. package org.springboot.sample;
  2. import static org.junit.Assert.assertArrayEquals;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springboot.sample.service.StudentService;
  6. import org.springframework.beans.factory.annotation.Autowired;
  7. import org.springframework.boot.test.SpringApplicationConfiguration;
  8. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  9. import org.springframework.test.context.web.WebAppConfiguration;
  10. /** * * @author 单红宇(365384722) * @myblog http://blog.csdn.net/catoop/ * @create 2016年2月23日 */
  11. @RunWith(SpringJUnit4ClassRunner.class)
  12. @SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
  13. @WebAppConfiguration
  14. public class StudentTest {
  15. @Autowired
  16. private StudentService studentService;
  17. @Test
  18. public void likeName() {
  19. assertArrayEquals(
  20. new Object[]{
  21. studentService.likeName("小明2").size() > 0,
  22. studentService.likeName("坏").size() > 0,
  23. studentService.likeName("莉莉").size() > 0
  24. },
  25. new Object[]{
  26. true,
  27. false,
  28. true
  29. }
  30. );
  31. // assertTrue(studentService.likeName("小明2").size() > 0);
  32. }
  33. }

接下来,你需要新增无数个测试类,编写无数个测试方法来保障我们开发完的程序的有效性。

2、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来运行你的代码。

3、参数化测试

Junit为我们提供的参数化测试需要使用 @RunWith(Parameterized.class)
然而因为Junit 使用@RunWith指定一个Runner,在我们更多情况下需要使用@RunWith(SpringJUnit4ClassRunner.class)来测试我们的Spring工程方法,所以我们使用assertArrayEquals 来对方法进行多种可能性测试便可。

下面是关于参数化测试的一个简单例子:

  1. package org.springboot.sample;
  2. import static org.junit.Assert.assertTrue;
  3. import java.util.Arrays;
  4. import java.util.Collection;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.junit.runners.Parameterized;
  8. import org.junit.runners.Parameterized.Parameters;
  9. @RunWith(Parameterized.class)
  10. public class ParameterTest {
  11. private String name;
  12. private boolean result;
  13. /**
  14. * 该构造方法的参数与下面@Parameters注解的方法中的Object数组中值的顺序对应
  15. * @param name
  16. * @param result
  17. */
  18. public ParameterTest(String name, boolean result) {
  19. super();
  20. this.name = name;
  21. this.result = result;
  22. }
  23. @Test
  24. public void test() {
  25. assertTrue(name.contains("小") == result);
  26. }
  27. /**
  28. * 该方法返回Collection
  29. *
  30. * @return
  31. * @author SHANHY
  32. * @create 2016年2月26日
  33. */
  34. @Parameters
  35. public static Collection<?> data(){
  36. // Object 数组中值的顺序注意要和上面的构造方法ParameterTest的参数对应
  37. return Arrays.asList(new Object[][]{
  38. {
  39. "小明2", true},
  40. {
  41. "坏", false},
  42. {
  43. "莉莉", false},
  44. });
  45. }
  46. }

4、打包测试
正常情况下我们写了5个测试类,我们需要一个一个执行。
打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。

代码如下:

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

5、使用Junit测试HTTP的API接口
我们可以直接使用这个来测试我们的Rest API,如果内部单元测试要求不是很严格,我们保证对外的API进行完全测试即可,因为API会调用内部的很多方法,姑且把它当做是整合测试吧。

下面是一个简单的例子:

  1. package org.springboot.sample;
  2. import static org.junit.Assert.assertNotNull;
  3. import static org.junit.Assert.assertThat;
  4. import static org.junit.Assert.assertTrue;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7. import org.hamcrest.Matchers;
  8. import org.junit.After;
  9. import org.junit.AfterClass;
  10. import org.junit.Before;
  11. import org.junit.BeforeClass;
  12. import org.junit.Ignore;
  13. import org.junit.Test;
  14. import org.junit.runner.RunWith;
  15. import org.springframework.beans.factory.annotation.Value;
  16. import org.springframework.boot.test.SpringApplicationConfiguration;
  17. import org.springframework.boot.test.TestRestTemplate;
  18. import org.springframework.boot.test.WebIntegrationTest;
  19. import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
  20. import org.springframework.util.LinkedMultiValueMap;
  21. import org.springframework.util.MultiValueMap;
  22. import org.springframework.web.client.RestTemplate;
  23. /** * * @author 单红宇(365384722) * @myblog http://blog.csdn.net/catoop/ * @create 2016年2月23日 */
  24. @RunWith(SpringJUnit4ClassRunner.class)
  25. @SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
  26. //@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
  27. @WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
  28. public class HelloControllerTest {
  29. private String dateReg;
  30. private Pattern pattern;
  31. private RestTemplate template = new TestRestTemplate();
  32. @Value("${local.server.port}")// 注入端口号
  33. private int port;
  34. @Test
  35. public void test3(){
  36. String url = "http://localhost:"+port+"/myspringboot/hello/info";
  37. MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
  38. map.add("name", "Tom");
  39. map.add("name1", "Lily");
  40. String result = template.postForObject(url, map, String.class);
  41. System.out.println(result);
  42. assertNotNull(result);
  43. assertThat(result, Matchers.containsString("Tom"));
  44. }
  45. }

6、捕获输出
使用 OutputCapture 来捕获指定方法开始执行以后的所有输出,包括System.out输出和Log日志。
OutputCapture 需要使用@Rule注解,并且实例化的对象需要使用public修饰,如下代码:

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

关于Assert类中的一些断言方法,都很简单,本文不再赘述。

但是在新版的Junit中,assertEquals 方法已经被废弃,它建议我们使用assertArrayEquals,旨在让我们测试一个方法的时候多传几种参数进行多种可能性测试。

发表评论

表情:
评论列表 (有 0 条评论,286人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Spring Boot Junit单元测试

    摘要: Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性。 凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部

    相关 Spring Boot Junit单元测试

    Junit这种老技术,现在又拿出来说,不为别的,某种程度上来说,更是为了要说明它在项目中的重要性。  凭本人的感觉和经验来说,在项目中完全按标准都写Junit用例覆盖大部分

    相关 Spring Boot 使用 junit 单元测试

    为什么要写测试用例  1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率 2. 可以自动测试,可以在项目打包前进行测试校验 3. 可以及时发现因为修改代码