Home > other >  How to mock a nested static class in java?
How to mock a nested static class in java?

Time:11-24

I'm trying to mock a nested static class but getting a NullPointerException. Is there any way we can do this.

Sample code: Parent Class

 class Parent {

        void record(String str) {
          **//Getting a NPE at this line when running test case**
            A.B.append(string);
        }
    }

Nested class

 class A {
        public static B b;

        public static class B {
            public void append(String str) {
              //perform some task
            }
        }
    }

Test class

    @ExtendWith(MockitoExtension.class)
    public class ParentTest {

        @InjectMock
        Parent parent;

        @Test
        public void dummy_test() {
            A.B writer = mock(A.B.class);
            doNothing().when(writer).append(any());
            parent.record("Text");
        }

    }

CodePudding user response:

@InjectMocks does not:

  • inject static fields.
  • inject fields to collaborating classes A

As your static field A.b is public, you can easily set it in a @BeforeEach method.

@ExtendWith(MockitoExtension.class)
public class ParentTest {

    Parent parent = new Parent();

    @Mock
    A.B writer;

    @BeforeEach
    void setup() {
        A.b = writer;
    }

    @Test
    public void dummy_test() {
        parent.record("Text");
    }

}
  • Related