英文:
junit testing without static methods
问题
我需要为各种不是静态的函数创建测试(我不被允许更改这些函数)。
例如:
public Double average(int[] scores) {
int sum = Arrays.stream(scores).sum();
return (double) sum / scores.length;
}
测试:
public void testAverage(){
int[] scores = {25, 100, 90, 72};
Double expected = 59.25;
Double result = LogicProblems.average(scores);
assertEquals(expected, result);
}
接口:
public Double average(int[] scores);
这样做会导致错误消息:"无法从静态上下文调用非静态方法"。
你能告诉我为什么上下文是静态的,以及如何解决/处理这个问题吗?
英文:
I need to create tests for various functions, which are not static (which I'm not allowed to change).
E.g.
public Double average(int[] scores) {
int sum = Arrays.stream(scores).sum();
return (double) sum/scores.length;
}
Test:
public void testAverage (){
int[] scores = {25, 100, 90, 72};
Double expected = 59.25;
Double result = LogicProblems.average(scores);
assertEquals(expected, result);
}
interface:
public Double average(int[] scores);
Doing so, I get the error message "can't call a non-static method from static context"
Could you tell me why the context is static, and how to work around/with it?
答案1
得分: 2
因为您无法更改LogicProblems
的代码,所以您需要在测试中实例化它:
public void testAverage () {
int[] scores = {25, 100, 90, 72};
Double expected = 59.25;
LogicProblems lp = new LogicProblemsImpl(); // 或者更好的方法是在@Before方法中
Double result = lp.average(scores);
assertEquals(expected, result);
}
英文:
Since you can't change the code of LogicProblems
, you need to instantiate it in the test:
public void testAverage (){
int[] scores = {25, 100, 90, 72};
Double expected = 59.25;
LogicProblems lp = new LogicProblemsImpl(); // Or better yet, in a @Before method
Double result = lp.average(scores);
assertEquals(expected, result);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论