java – Mockito:将真实对象注入到@Autowired私有字段

我使用Mockito的@Mock和@InjectMocks注释注入依赖关系到私有字段,注释用Spring的@Autowired:

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Mock
    private SomeService service;

    @InjectMocks
    private Demo demo;

    /* ... */
}

public class Demo {

    @Autowired
    private SomeService service;

    /* ... */
}

现在我也想注入真正的对象到私人@Autowired字段(没有setters)。这是可能的还是仅限于注入Mocks的机制?

使用@Spy注释

@RunWith(MockitoJUnitRunner.class)
public class DemoTest {
    @Spy
    private SomeService service = new RealServiceImpl();

    @InjectMocks
    private Demo demo;

    /* ... */
}

Mockito将考虑所有具有@Mock或@Spy注释的字段作为注入到使用@InjectMocks注释注释的实例的潜在候选。在上面的情况下,’RealServiceImpl’实例将被注入到’demo’

有关详细信息,请参阅

http://docs.mockito.googlecode.com/hg/org/mockito/Mockito.html#13
http://docs.mockito.googlecode.com/hg/latest/org/mockito/Spy.html

http://stackoverflow.com/questions/20270391/mockito-inject-real-objects-into-private-autowired-fields

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:java – Mockito:将真实对象注入到@Autowired私有字段