Using JMockit to mock autowired interface implementations

前端 未结 5 517
暖寄归人
暖寄归人 2020-12-17 18:10

We are writing JUnit tests for a class that uses Spring autowiring to inject a dependency which is some instance of an interface. Since the class under test never explicitly

5条回答
  •  情书的邮戳
    2020-12-17 18:40

    JMockit will always instantiate a mocked interface (except in the case of a final mock field), but that only occurs in test code. It will not automatically inject the instance into code under test.

    You would have to manually inject the mock instance. For example:

    public class SomeTest
    {
       @Autowired UnitUnderTest unitUnderTest;
       @Mocked ISomeInterface theMock; // created and assigned automatically
    
       @Test
       public void testSomeMethod()
       {
          Deencapsulation.setField(unitUnderTest, theMock);
          //proceed with unit test here
       }
    }
    

    mockit.Deencapsulation is a Reflection-based utility class that lets you invoke private methods, get/set fields, etc.

提交回复
热议问题