1

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
  • 1
    If you want to call a non-static method defined in the LogicProblems class, you need to use an instance of LogicProblems. That's what not being static means. Depending on how the class is written it might be as simple as new LogicProblems().average(scores) Commented Jul 31, 2020 at 20:49

1 Answer 1

2

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);
}
Sign up to request clarification or add additional context in comments.

5 Comments

when I try the latter, it says that lp is abstract and cannot be instantiated
@idanicoleherbert presumably you have a concrete class that extends it you can use?
I have a class that implements it, but if i change the implementation methods to static, it gives me the error that I can't override the instance method "average int[]"
@idanicoleherbert you need to instantiate the concrete class that extends LogicProblems. I've edited my answer to demonstrate that under the assumption it's called simply LogicProbelmsImpl. If it's called something else, just replace the name (and pass the necessary arguments to its constructor if it requires any)
Understood. Thanks, it now works. I appreciate you're help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.