junit测试无静态方法

huangapple go评论75阅读模式
英文:

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

huangapple
  • 本文由 发表于 2020年8月1日 04:45:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/63198876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定