Soory
Soory

Reputation: 1

Error: method X must override or implement a supertype method

I'm using JUnit 5, and copied the code from "Software Testing" book in order to create a mock object for testing. part of the tester code is:

 @Test
 public void rangesOKTestWithoutDependency() {
    // This is an anonymous class
    SimpleDate simpleDate = new SimpleDate(1, 1, 2000) {
         @Override
         public boolean isLeap(int year) {               
             if(2000 == year) return true;
             else if(2001 == year) return false;
            else throw new IllegalArgumentException("No Mock for year " + year);
         }
 };
 assertTrue(simpleDate.rangesOK(2, 29, 2000)); // Valid due to leap year
 assertFalse(simpleDate.rangesOK(2, 29, 2001)); // Valid due to leap year
 }

I have a compiler error, which says "Method isLeap(int) must override or implement a supertype method". This error is reported in the line that I override isLeap() method. (The line below @override)

Well, amazingly this is what I have done. So I don't know what is this complain about. Here is the isLeap() method in class simpleDate:

private boolean isLeap(int year) {
           boolean isLeapYear = true;
           if(year % 4 != 0)
                 isLeapYear = false;
           else if(year % 100 != 0)
                 isLeapYear = true;
           else if(year % 400 != 0)
                 isLeapYear = false;
           return isLeapYear;
    }

As you see the method in the tester is an overridden version of the original method but still I get an error. Any thoughts?

ps: I'm using eclipse.

Upvotes: 0

Views: 3698

Answers (2)

Soory
Soory

Reputation: 1

What I intended to do is to test a "private" method, which of course is not visible. Since it is not visible, I cannot override it. So the error that I got, makes complete sense.

I solved the problem of testing private method by using java.lang.reflect The idea came from this paper.

Now, what I'm thinking is how to solve the same problem for other languages that do not provide a similar API. In other words, how to create a mock object for the purpose of testing, if possible at all, to circumvent the invisibility of a method

Upvotes: 0

ProDec
ProDec

Reputation: 5410

A private method in superclass is not visible to subclass. You need to either remove the @Override annotation or change your method in SimpleDate to protected to remove the compilation error.

Removing the @Override does not affect the superclass, the two isLeap methods do not have overriding relation.

Changing the method in SimpleDate to protected, the method in subclass will indeed override the one in superclass.

Upvotes: 1

Related Questions