简体   繁体   中英

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.

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

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