如何通过InjectMocks注解注入真实对象

How to inject real objects through InjectMocks annotation

我有一个场景,其中 class 中有两个属性,其中一个 属性 是真实的,另一个是模拟的如何将这两个属性注入对象。

例如

    @RunWith(MockitoJUnitRunner.class)
    public class SampleTest extends ExchangeTestSupport {

        @InjectMocks
        private SampleTest sampleTest ;

        private SampleProperties properties;
        @Mock
        private SampleProvider provider;
}

在上面的代码中,属性是真实的,提供者是模拟的,需要将两者都注入到 sampleTest 对象中。

添加@Spy注入真实对象

 @Spy
 private SampleProperties properties;

A field annotated with @Spy can be initialized explicitly at declaration point. Alternatively, if you don't provide the instance Mockito will try to find zero argument constructor (even private) and create an instance for you.

如果您正在使用 Spring 上下文,还要添加 @Autowired 注释