Renukaradhya
Renukaradhya

Reputation: 862

Writing Junit Testcase for a default method in an Interface

I am using Java 1.8 and using default method in Interface. As we are targeting to write JUnit for all the methods we have I have a situation that need to write Junit for default method. Can somebody help me please to know whether we can achieve it.

My Interface is below.

 public interface DataFilter {

   default public TableInclusions parseYaml(String path) throws IOException {

    Resource resource = new ClassPathResource(path);
    Yaml yaml = new Yaml();
    yaml.setBeanAccess(BeanAccess.FIELD);
    return yaml.loadAs(resource.getInputStream(), TableInclusions.class);
   }

   public DBMSEvent filter(DBMSEvent jsonString) throws FilterException;

   public void setYaml(String path);
}

Should I need to write Junit for the method of the class which implements this Interface and uses this default method to test it?

Upvotes: 2

Views: 1136

Answers (1)

Bob Brinks
Bob Brinks

Reputation: 1392

In your test you could do:

DataFilter dataFilter = new DataFilter() {
//Add no-op implementation for other methods
};
datafilter.parseYaml(testPath);

But looking add your interface I don't think you should have this default method at all. I think it would be better to inject a TableInstructorParser with this method in it. That would be better for your separation of concerns.

Upvotes: 5

Related Questions