# junit测试无静态方法

go评论44阅读模式

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

``````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);
}
``````

• 本文由 发表于 2020年8月1日 04:45:22
• 转载请务必保留本文链接：https://go.coder-hub.com/63198876.html
• compiler-errors
• java
• junit
• static
• testing

go 46

go 47

go 34

go 55