Junit4使用详解

432 阅读3分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

Junit4启动注解说明

  1. 首先是针对传统的xml配置文件的单元测试注解

使用xml配置文件,且没有配置类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:application-content.xml")
public class XXXXTest {
}
  1. 使用配置类且配置文件格式为.properties或.yml格式的单元测试主键

一般是SpringBoot 应用,否则会容易加载不到配置类而启动失败

如果SpringBootTest注解不指定classes 参数或者指定的classes参数不是启动main函数入口SpringBootTest(classes = SpringTestAutoConfig.class),则会自动从当前测试类包一层一层向上检索,直到找到@SpringBootApplication或@SpringBootConfiguration注释类为止。以此来启动Spring Boot应用,并装载Spring上下文。

@RunWith(SpringJUnit4ClassRunner.class)
//@SpringBootTest //不指定classes参数也是可以的
@SpringBootTest(classes= Application.class)
public class BBBBXXXXXTest {
}

Junit4测试注解说明

  1. @BeforeClass和@AfterClass在类被实例化前(构造方法执行前)就被调用了,而且只执行一次,通常用来初始化和关闭资源。

  2. @Before和@After和在每个@Test执行前后都会被执行一次。

  3. @Test标记一个方法为测试方法单元,被@Ignore标记的测试方法不会被执行。

    @Autowired
    XXXMapper mapper;

    @Test
    public void insert() {
        Data data = new Data ();
        mapper.Insert(data);
    }

    @Test
    @Ignore //不被执行的测试方法
    public void delete() {
    }

依赖测试

@Test (dependsOnMethods = {“testMethod2”}) //可以保证先执行testMethod2再执行该方法\
特定顺序执行测试用例\
@Test (priority = 1) //priority从0开始,0优先级最高```
@Test(timeout=1000)   //一个测试用例比起指定的毫秒数花费了更多的时间,那么 Junit 将自动将它标记为失败
@Test(expected = ArithmeticException.class)  //unit 用代码处理提供了一个追踪异常的选项。你可以测试代码是否它抛出了想要得到的异常。

JUnit 断言

junit所有的断言都包含在 Assert 类中。

这个类提供了很多有用的断言方法来编写测试用例。只有失败的断言才会被记录。Assert 类中的一些有用的方法列式如下:

void assertEquals(boolean expected, boolean actual) //检查两个变量或者等式是否平衡
void assertTrue(boolean expected, boolean actual) //检查条件为真
void assertFalse(boolean condition) //检查条件为假
void assertNotNull(Object object)   //检查对象不为空
void assertNull(Object object)      //检查对象为空
void assertSame(boolean condition)  //assertSame() 方法检查两个相关对象是否指向同一个对象
void assertNotSame(boolean condition) //assertNotSame() 方法检查两个相关对象是否不指向同一个对象
void assertArrayEquals(expectedArray, resultArray) //assertArrayEquals() 方法检查两个数组是否相等

Junit性能测试

java 性能测试框架工具-JunitPerf

@Rule
public JUnitPerfRule perfTestRule = new JUnitPerfRule();

# 性能测试单元测试
@Test
@JUnitPerfTest(threads = 2, durationMs = 5000)
@JUnitPerfTestRequirement()
public void testJunitPerf() {
    // todo your code just like interface test
}

JUNITBENCHMARK JUNIT性能测试

#性能测试maven依赖
<dependency>
        <groupId>javolution</groupId>
        <artifactId>javolution</artifactId>
        <version>5.4.5</version>
</dependency>

测试代码

import com.carrotsearch.junitbenchmarks.AbstractBenchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import javolution.text.TextBuilder;
import org.junit.Test;
 
/**
 * Benchmark for String concatenation. Compares StringBUilder (JDK) and
 * TextBuilder (Javolution).
 */
public class StringConcatenationBenchmark extends AbstractBenchmark {
    public static final long LOOPS_COUNT = 10000000;
    @Test
    @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1)
    public void stringBuilderBenchmark()  {
        StringBuilder builder = new StringBuilder();
        for (long i = 0; i < LOOPS_COUNT; i++) {
            builder.append('i').append(i);
        }
        System.out.println(builder.toString().length());
    }
    
    @Test
    @BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 1)
    public void textBuilderBenchmark()  {
        
        TextBuilder builder = new TextBuilder();
        for (long i = 0; i < LOOPS_COUNT; i++) {
            builder.append('i').append(i);
        }
        System.out.println(builder.toString().length());
    }
}

参考资料:

  1. SpringBoot单元测试

  2. springboot的注解的作用说明