Java:不同参数排序的测试方法 [英] Java: test methods of different parameter orderings
问题描述
无论参数顺序如何,我都想正确验证方法.
I want to correctly validate a method regardless of the parameter ordering.
因此,代码段 1 和 2 都应该通过代码段 3 中的测试用例.
Therefore, snippet 1 and 2 should both pass the test case in snippet 3.
(片段 1)
public Integer compute_speed(Integer distance, Integer time) {
return distance/time;
}
(片段 2)
public Integer compute_speed(Integer time, Integer distance) {
return distance/time;
}
您可以假设这两个片段是两个学生提交的不同代码.并且您可以假设参数的数量可以多达 10 个.
在测试用例中,我写道,
In the test case, I wrote,
(片段 3)
return compute_speed(3, 1).equals(3);
这验证了代码段 1,但失败了 2.我怎样才能使两个代码段都通过测试用例?
This validates snippet 1 but fails for 2. How can I make it such that both snippets pass the test case?
如果有类似的东西,
return compute_speed(distance = 3, time = 1).equals(3);
提前致谢...
推荐答案
更简洁的方法是使用 Integer computeSpeed(Integer time, Integer distance);
方法创建接口:
A cleaner way would be to create an interface with a Integer computeSpeed(Integer time, Integer distance);
method:
public interface DistanceCalculator {
Integer computeSpeed(Integer distance, Integer time);
}
然后您要求学生实现它并调用他们的实现 StudentNameDistanceCalculator.例如,您将收到学生的以下课程:
You then ask the students to implement it and call their implementation StudentNameDistanceCalculator. For example you will receive the following classes from your students:
public class AssyliasDistanceCalculator implements DistanceCalculator {
public Integer computeSpeed(Integer distance, Integer time) {
return distance / time;
}
}
public class BobDistanceCalculator implements DistanceCalculator {
public Integer computeSpeed(Integer distance, Integer time) {
return distance / time * 2;
}
}
然后您可以在一个项目中加载他们的所有类并一次测试所有类.以 TestNg 为例:
You can then load all their classes in one project and test all the classes at once. For example with TestNg:
@Test(dataProvider = "students")
public void testMethod(Class<?> clazz) throws Exception {
DistanceCalculator dc = (DistanceCalculator) clazz.newInstance();
assertEquals(dc.computeSpeed(3, 1), (Integer) 3,
clazz.getSimpleName().replace("DistanceCalculator", "") + " failed");
}
@DataProvider(name = "students")
public Object[][] dataProvider() {
return new Object[][]{
{AssyliasDistanceCalculator.class},
{BobDistanceCalculator.class}};
}
你会得到一份关于谁没有通过测试的详细报告:
And you will get a detailed report of who doesn't pass the test:
这篇关于Java:不同参数排序的测试方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!