jeudi 31 décembre 2020

Checking for Method existence JUnit

I'm writing unit tests for a class A:

public class A {
   public void sayHello() {
      System.out.println("Hello!");
   }
}

I want to test method sayHello within A as follows:

public class Test {
   void test() {
      A a = new A();
      assertEquals(a.sayHello(), "Hello!");
   }
}

The issue is that sayHello might not exist in class A, which would cause this unit test to break. I want to prevent this behavior by failing the test prematurely if sayHello doesn't exist, which I tried to do by modifying test as:

public class Test {
   void test() {
      try {
         A a = new A();
         assertEquals(a.sayHello(), "Hello!");
      } catch (NoSuchMethodException e) {
          fail("sayHello doesn't exist);
      }
   }
}

This doesn't seem to work as the method doesn't compile! Is there a workaround to please the Java compiler? Note that I really want to keep a similar structure here by directly calling sayHello and I don't want to use call sayHello.invoke() because I already have a large codebase with code like this!





Aucun commentaire:

Enregistrer un commentaire