我想进行如下的批量测试,但是如果出现错误,则不会告诉我错误发生在i
的哪个值。
@Test
public void simpleMovingAverageBatch() {
for (int i = 1; i < 61; ++i) {
simpleMovingAverage(i);
}
}
public void simpleMovingAverage(int days) {
double sma = -1;
int size = stock.getCloses().size();
stock.calcSMA(days); // <- code that I'm testing
// first days should be -1
for (int index = size - 1; index >= size - days + 1; --index) {
assertEquals(-1, stock.getSMA(days, index), 0.001);
}
for (int index = size - days - 1; index >= 0; --index) {
sma = 0.0;
for (int i = 0; i < days; ++i) {
sma += stock.getCloses().get(index + i);
}
sma /= days;
assertEquals(sma, stock.getSMA(days, index), 0.001);
}
}
这是一个如果我按原样运行代码会发生什么的例子:
这是我想要发生的事情的一个例子:
我已经看过参数化测试in this tutorial,但我不知道这是否是我想要的路线。
任何提示?
我不认为这个问题与这些问题重复:
Running the same JUnit test case multiple time with different data
答案 0 :(得分:2)
进行此测试的正确方法是使用您在问题中描述的参数化测试。但是,你说你不想这样做。因此,您可以始终使用String message参数作为失败消息。
您似乎在此行中使用assertEquals(double, expected, double actual, double delta)
:
assertEquals(-1, stock.getSMA(days, index), 0.001);
相反,您可以使用assertEquals(String message, double expected, double actual, double delta)
为自己提供更具信息性的错误消息,例如
assertEquals(String.format("For index %d,", index), -1, stock.getSMA(days, index), 0.001);
这会给您一条错误消息:
java.lang.AssertionError: For index 15, expected:<-1.0> but was:<0.0>
答案 1 :(得分:2)
Durron's answer leads to parameterized JUnit tests via @Parameters
. This is a great answer and fits the question perfectly. However, I've been down that road and found it created complicated and hard to read tests.
Theories are an alternative within JUnit: junit.org/apidocs/org/junit/experimental/theories/Theories.html
If you are willing to stray from JUnit, testNG's dataproviders are quite versatile: testng.org/doc/documentation-main.html#parameters-dataproviders
答案 2 :(得分:2)
试试JUnitParams。您的测试将如下所示:
@RunWith(JUnitParamsRunner.class)
public class ExampleTest {
// this method provides parameters for simpleMovingAverage
public static Iterable<Integer> parametersForSimpleMovingAverage() {
return IntStream.rangeClosed(1, 61).boxed().collect(Collectors.toList());
}
@Parameters
@Test
public void simpleMovingAverage(int days) {
double sma = -1;
int size = stock.getCloses().size();
stock.calcSMA(days); // <- code that I'm testing
// first days should be -1
for (int index = size - 1; index >= size - days + 1; --index) {
assertEquals(-1, stock.getSMA(days, index), 0.001);
}
for (int index = size - days - 1; index >= 0; --index) {
sma = 0.0;
for (int i = 0; i < days; ++i) {
sma += stock.getCloses().get(index + i);
}
sma /= days;
assertEquals(sma, stock.getSMA(days, index), 0.001);
}
}
当你进行测试时,你会得到一份你想要的报告。更好的是,与标准的JUnit Parametrized运行器不同,JUnitPramsRunner报告不仅包含测试用例索引,还包含每个案例的参数(抱歉,我没有足够的声誉发布截图)。
注意:您需要添加依赖项:
摇篮:
testCompile 'pl.pragmatists:JUnitParams:1.0.2'
的Maven:
<dependency>
<groupId>pl.pragmatists</groupId>
<artifactId>JUnitParams</artifactId>
<version>1.0.4</version>
<scope>test</scope>
</dependency>