Search code examples
javaunit-testingjmockit

Jmockit @Mocked inside a helper class doesn't initialize


If I have the following;

public class ClassA {

   public void methodA(){
    System.out.println("In ClassA, methodA");
  }
}
public class ClassB {

  public void methodB(){
  }
}

and a junit test of;

@Test
public void testMocked(@Mocked final ClassB mockedB) {
    System.out.println("Mocked inline");
    new MockUp<ClassA>() {
        @Mock
        public void methodA() {
            System.out.println("Inline mockup, mockedB:" + mockedB);
        }
    };
    ClassA a = new ClassA();
    a.methodA();

}

Then when I run the test I get;

Mocked inline
Inline mockup, mockedB:jmockitpractice.ClassB@329b0985

Which is as expected, the classB is Mocked, and an instance is available.

But, if I change this to create a helper class for mocking,

public class MockHelper {
  @Mocked ClassB classB;
  public void setupMocks(){

    new MockUp<ClassA>() {

        @Mock
        public void methodA(){
            System.out.println("In setupMocks, classB:"+classB);
        }
    };
  }
}

and the junit becomes;

@Test
public void testMockedInClass() {
    System.out.println("Mocked in helper class");
    MockHelper mh = new MockHelper();
    mh.setupMocks();
    ClassA a = new ClassA();
    a.methodA();

}

the result I get is;

Mocked in helper class
In setupMocks, classB:null

classB is not initialized by the @Mocked inside MockHelper

I would like to have all the mocking in a helper class, rather than having to declare all the mocking in the test class. Any ideas why this doesn't work? Thanks.


Solution

  • Thanks Dom Farr, the answer was inheritance.

    public class MockHelper {
    
    @Mocked
    ClassB classB;
    
    public void setupMocks() {
    
        new MockUp<ClassA>() {
    
            @Mock
            public void methodA() {
                System.out.println("In setupMocks, classB:" + classB);
            }
        };
    }
    }
    

    and public class mockTest extends MockHelper {

    @Test
    public void testMockedInClass() {
        System.out.println("Mocked in helper class");
        setupMocks();
        ClassA a = new ClassA();
        a.methodA();
    
    }
    
    }
    

    As the test class extends the helper, it now works;

    Mocked in helper class
    In setupMocks, classB:jmockitpractice.ClassB@5d54e317