java - 对列表中的每个元素运行 jUnit 测试
问题描述
我有大量的测试,如下所述:
预期值 (y_position_expected) 被硬编码到 jUnit 测试中。测试将一个值 (x_position) 发送到一个方法,该方法进行一些统计并返回结果 (y_position_actual)。此结果是与预期值进行比较的实际值。
public class PositionNormalizerTest {
public Normalizers norman ;
@Before
public void beforeFunction() {
norman = DislocationUtils.getPositionService().getNormalizers() ;
}
@Test
public void testAmountForNumberString1() {
String y_position_expected = 100.0d ;
double x_position = <A DOUBLE GOES HERE> ;
double y_position_actual = norman.normalizeYPosition(x_position).getAmount() ;
assertEquals(y_position_expected, y_position_actual, 0.001) ;
}
}
x_position 的值来自地图的值,该地图要大得多,但类似于下图:
checkpoints = {"alpha":[0.0d, 10.0d,200.0d], "beta":[50.0d, 44.0d,12.0d]}
此映射的键是字符串,值是双精度列表。因此,必须针对每个值中的每个元素运行测试。
问题:
鉴于地图(检查点)的大小和测试的数量,手动创建所有测试需要很长时间。因此,我正在寻找一种方法来使具有多个测试用例的单个 jUnit 测试类自动迭代映射的值并运行测试。我尝试了正常循环,但是一旦断言得出结论,它可能是失败还是通过,测试用例结束而不继续循环。有没有办法做到这一点?我可以使用注释来做到这一点吗?谢谢。
解决方案
使用参数化测试:
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.Parameter;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class PositionNormalizerTest {
@Parameters
public static Collection<Object[]> data() {
//here you create and return the collection of your values
return Arrays.asList(new Object[][]{{"alpha", 0.0d, 10.0d, 200.0d}, {"beta", 50.0d, 44.0d,12.0d}});
}
@Parameter
public String key; //alpha
@Parameter(1)
public double d1; //0.0d
@Parameter(2)
public double d2; //10.0d
@Parameter(3)
public double d3; //200.0d
@Test
public void test() {
//here's your test
//this method will be executed for every element from the data list
}
}
您可以在此处获取有关参数化测试的更多信息:参数化测试
推荐阅读
- python - Numpy 函数在使用 np.where() 时给出了意外的输出
- nginx - 负载均衡器的 nginx 访问日志中的 upstream_addr 何时为“-”?
- asp.net - 如何为身份服务器启用内容安全策略?
- django - 我无法使用 Django 应用程序中的静态文件
- android - Android 无法从 passpoint 配置文件验证 CA 证书
- javascript - 无法在电子中正确渲染材料选择元素
- javascript - Node 上的 Javascript textContent 不返回 unicode 字符
- android - 当应用程序在 android 中被杀死时,alarmmanger 有时会工作或不工作
- azure - 使用 Azure B2C 调用 Microsoft 图形 API
- python - 如何在 Azure Blob 中上传大字符串?