0

I'm very new to writing unit tests for java. I want to write a test for method1:

public ClassA {
   public String method1() {
      ClassB classInst = ClassB.getInstance()
      return classInst.doSomething()
   }
}

Here, doSomething in classB connects to some databases and does an operation. This is my test class:

public TestClassA {
   @Mock
   private ClassB classBInst = mock(ClassB.class)

   @InjectMocks
   private ClassA classAInst = new ClassA()

   @Before
   public void setup() {
      when(classInst.isClientEnabled()).thenReturn("ReturnStr");
   }

   @Test
   public void testMethod1() {
      String result = classAInst.method1();
      assertEquals(result, "ReturnStr")
   }

}

But the assert is failing because ClassB.doSomething() is not returning the mocked return value. Am I doing something wrong here? What is the correct way to mock classB here? I am using junit4 and mockito here

baggy696
  • 37
  • 7
  • How `ClassB` looks like? – Youcef LAIDANI Nov 11 '22 at 10:12
  • In class A, you dare calling a `static` method to get your instance of ClassB, so `InjectMocks` won’t help you with that. What you want to do instead is described here : https://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito – racraman Nov 11 '22 at 10:13
  • Oh okay. So I should use powerMockito for this? – baggy696 Nov 11 '22 at 10:16
  • No, powermockito is old - mockito has been extended to mock static methods, as described in that answer, or here for more details : https://www.baeldung.com/mockito-mock-static-methods – racraman Nov 11 '22 at 10:37
  • Instead of “old”, rather PowerMockito has issues with Junit5. Best to stick with pure Mockito where possible (including the mocking of static methods) – racraman Nov 11 '22 at 10:46
  • Consider making your class more test-friendly. Instead of reaching for the singleton instance of ClassB, you could store it as a field - preferably initialized in a constructor – Lesiak Nov 11 '22 at 16:33

0 Answers0