Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
186 views
in Technique[技术] by (71.8m points)

java - 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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...