Junit 这种老技术, 现在又拿出来说, 不为别的, 某种程度上来说, 更是为了要说明它在项目中的重要性.
凭本人的感觉和经验来说, 在项目中完全按标准都写 Junit 用例覆盖大部分业务代码的, 应该不会超过一半.
刚好前段时间写了一些关于 SpringBoot 的帖子, 正好现在把 Junit 再拿出来从几个方面再说一下, 也算是给一些新手参考了.
那么先简单说一下为什么要写测试用例
1. 可以避免测试点的遗漏, 为了更好的进行测试, 可以提高测试效率
2. 可以自动测试, 可以在项目打包前进行测试校验
3. 可以及时发现因为修改代码导致新的问题的出现, 并及时解决
那么本文从以下几点来说明怎么使用 Junit,Junit4 比 3 要方便很多, 细节大家可以自己了解下, 主要就是版本 4 中对方法命名格式不再有要求, 不再需要继承 TestCase, 一切都基于注解实现.
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);
- }
- }
接下来, 你需要新增无数个测试类, 编写无数个测试方法来保障我们开发完的程序的有效性.
- // 在所有测试方法前执行一次, 一般在其中写上整体初始化的代码
- @BeforeClass
- // 在所有测试方法后执行一次, 一般在其中写上销毁和释放资源的代码
- @AfterClass
- // 在每个测试方法前执行, 一般用来初始化方法 (比如我们在测试别的方法时, 类中与其他测试方法共享的值已经被改变, 为了保证测试结果的有效性, 我们会在 @Before 注解的方法中重置数据)
- @Before
- // 在每个测试方法后执行, 在方法执行完成后要做的事情
- @After
- // 测试方法执行超过 1000 毫秒后算超时, 测试将失败
- @Test(timeout = 1000)
- // 测试方法期望得到的异常类, 如果方法执行没有抛出指定的异常, 则测试失败
- @Test(expected = Exception.class)
- // 执行测试时将忽略掉此方法, 如果用于修饰类, 则忽略整个类
- @Ignore("not ready yet")
- @Test
- @RunWith
- 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},
- });
- }
- }
- @RunWith(Suite.class)
- @SuiteClasses({ATest.class, BTest.class, CTest.class})
- public class ABCSuite {
- // 类中不需要编写代码
- }
- 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"));
- }
- }
- @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"));
- }
- }
来源: http://www.bubuko.com/infodetail-3257875.html