本篇来学习两个参数项,异常和超时。这两个参数是结合@Test来使用的,作用范围当然是测试方法。
1.异常Exception
有时候我们执行这个方法,出现异常是期待的结果,单元测试中如果出现异常,会中断测试,为了不中断,我们需要使用异常注解
模拟异常测试
为了模拟异常,我们需要到被测项目中,某一个方法写一个抛异常的代码,然后这个自定义异常类需要我们写以下。
编辑被测项目的TrackingService.java 把setGoal方法改成这样
public void setGoal(int value) throws InvalidGoalException{
if(value < 0) {
throw new InvalidGoalException();
}
goal = value;
}
package com.anthony.protein;
public class InvalidGoalException extends Exception {
}
这个类啥也不写,就是这样。然后我们来写一个测试用例,测试这个异常。
package test;
import static org.junit.Assert.*;
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 com.anthony.protein.InvalidGoalException;
import com.anthony.protein.TrackingService;
public class TrackingServiceTests {
private TrackingService ts;
@BeforeClass
public static void before() {
System.out.println("Before class, Onln Once");
}
@AfterClass
public static void after() {
System.out.println("After class, only once");
}
@Before
public void setup() {
System.out.println("Before Method");
ts = new TrackingService();
}
@After
public void tearDown() {
System.out.println("After Method");
}
@Test
public void newTrackingServiceTotalIsZero() {
assertEquals("Tracking service total was not zero", 0, ts.getTotal());
}
@Test
public void whenAddingProteinTotalIsIncreaseByAmount() {
ts.addProtein(10);
assertEquals(10, ts.getTotal());
}
@Test
public void whenRemovingProteinTotalRemainsZero() {
ts.removeProtein(5);
assertEquals(0, ts.getTotal());
}
@Test(expected=InvalidGoalException.class)
public void testExceptionThrow() throws InvalidGoalException {
ts.setGoal(-5);
}
}
最后一条异常抛出测试,如果没有这个功能,我们这个用例就是会报错。但是实际上测试异常场景也是测试用例一部分,这个用例出现异常应该是期待的结果。
2.Timeout 超时
有时候某些方法对性能要求很高,我们需要测试这个用例执行时间,如果超过一个时间阈值,说明这个方法性能有问题,这个时候我们可以使用Timeout=时间阈值来做这个场景。
在上面的单元测试类中添加一个测试用例
@Test(timeout=20)
public void badTest() throws InvalidGoalException {
for(int i=0; i < 1000000000; i++) {
ts.setGoal(1);
}
}
意思就是,如果运行这个方法好使大于20毫秒,这个用例就会失败。
3.断言
在Junit中,以下是常见的断言方法,断言就是测试中比较期待结果和实际结果的一个步骤,其实断言很难写的,不好写。
assertArrayEquals
assertEquals
assertTrue
assertFalse
assertNull
assertNotNull
assertSame
assertNotSame
fail
这里就不带大家一个一个去练习,其实用得最多应该是第2 3 4 5 6这几个。