这篇学习注解@Theory和@DataPoint, 这个和Parameters一样,属于数据驱动范畴。
1.Theory
@DataPoint标注的也是一个静态方法,里面有数据源。如果是@DataPoint表示一个数据,如果是@DataPoints表示一组数据,一般用@DataPoints
2.demo练习
新创建一个测试类,代码如下
package test;
import static org.junit.Assert.assertTrue;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import com.anthony.protein.TrackingService;
@RunWith(Theories.class)
public class TheoryTests {
@DataPoints
public static int[] data() {
return new int[] {
1, 5, 10, 50, 4
};
}
@Theory
public void testThory(int value) {
TrackingService ts = new TrackingService();
ts.addProtein(value);
assertTrue(ts.getTotal() > 0);
}
}
运行以下,出现失败,是因为有一个value=-4,所以失败,可以把这个负数改成正数就运行成功。或者这里可以使用Assume方法来过滤到不符合条件的测试结果,这样也能运行成功。
package test;
import static org.junit.Assert.assertTrue;
import org.junit.Assume;
import org.junit.experimental.theories.DataPoints;
import org.junit.experimental.theories.Theories;
import org.junit.experimental.theories.Theory;
import org.junit.runner.RunWith;
import com.anthony.protein.TrackingService;
@RunWith(Theories.class)
public class TheoryTests {
@DataPoints
public static int[] data() {
return new int[] {
1, 5, 10, 50, -4
};
}
@Theory
public void testThory(int value) {
TrackingService ts = new TrackingService();
ts.addProtein(value);
// assume的作用是不执行一些不符合条件的组合,一般和theoryies一起使用
Assume.assumeTrue(value>0);
assertTrue(ts.getTotal() > 0);
}
}
这个@Theory和@Parameters确实有一点像,可以回去复习下https://blog.csdn.net/u011541946/article/details/95009227
虽然@Theory不常用,我个人认为@Theory比@Parameters好处在于,在@Parameters中运行报错,没有显式告诉你数据源中哪一个参数运行出了问题。下面直接指出了-4这个数据失败。