简体   繁体   中英

junit testing without static methods

I need to create tests for various functions, which are not static (which I'm not allowed to change). Eg

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM