简体   繁体   中英

Mock method on a new instance

I am trying to create Junit test case using Mockito framework and junit5. I am working on the below code:

    Class ClasstToBeTested {
      FirstClass a = new FirstClass();

      public String methodToBeTested() {
         String str = a.firstMethod();
         return str;
      }
    }

   Class FirstClass {
      SecondClass b = new SecondClass();

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

I have a class structure like above and I need to mock secondMethod.

I tried @spy on FirstClass and mocked SecondClass and secondMethod, but mocking didn't happen. How can I mock in this case?

Note - I am not in a position to change the structure of the class.

You have some options:

  1. (Preferred) Use IoC dependency injection to supply the SecondClass instance instead of building it inside FirstClass :
  class FirstClass {
      private final SecondClass b;

      // Injecting the SecondClass instance
      FistClass(SecondClass b) {
          this.b = b;
      }

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

Then you can just inject a mock in your test.

  1. Add a SecondClass setter just for tests.
   class FirstClass {
      SecondClass b = new SecondClass();

      // Annotate with a visibility for test annotation if available.
      // Here one can inject a mock too, but can cause problems if used inadvertently.
      void setSecondClassForTests(SecondClass b) {
         this.b = b;
      }

      public String firstMethod() {
          String str = b.secondMethod();
          return str;
      }
   }

Then you call the setter on the test and pass the mock.

  1. Use reflection to get the field and set a mock. Something like (In your test function):
final Field declaredField = instanceOfFirstClass.getClass().getDeclaredFields("b");
declaredField.setAccessible(true);
declaredField.set(instanceOfFirstClass, yourMockedInstance);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM