Using JMockit to mock autowired interface implementations

前端 未结 5 515
暖寄归人
暖寄归人 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:38

    If you have a @Qualifier annotation for the interface, you need to name your @Injectable field exactly as it is named in qualifier.

    Here is quote from JMockit doc:

    Custom names specified in field annotations from Java EE (@Resource(name), @Named) or the Spring framework (@Qualifier) are used when looking for a matching @Injectable or @Tested value. When such a name contains a - (dash) or . (dot) character, the corresponding camel-cased name is used instead.

    For example:

    @Component
    public class AClass {
    
       @Autowired
       private Bean1 bean1;
    
       @Autowired
       @Qualifier("my-dashed-name")
       private AmqpTemplate rpcTemplate;
    }
    

    Unit test class:

    public class AClassTest {
    
       @Injectable
       private Bean1 bean1;
    
       @Injectable
       private AmqpTemplate myDashedName;
    
       @Tested
       private AClass aClass = new AClass();
    }
    

    Also there is no need to use setFiled for each @Autowired bean, all fields injects automatically when @Tested class instantiated. Tested on JMockit ver. 1.30

提交回复
热议问题