嗨,我正在使用Mockito来测试我的Spring项目,但@InjectMocks
似乎没有将一个模拟服务注入到另一个Spring服务(bean)中.
这是我要测试的Spring服务:
@Service public class CreateMailboxService { @Autowired UserInfoService mUserInfoService; // this should be mocked @Autowired LogicService mLogicService; // this should be autowired by Spring public void createMailbox() { // do mething System.out.println("test 2: " + mUserInfoService.getData()); } }
以下是我想要模拟的服务:
@Service public class UserInfoService { public String getData() { return "original text"; } }
我的测试代码在这里:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/spring/root-context.xml" }) public class CreateMailboxServiceMockTest { @Mock UserInfoService mUserInfoService; @InjectMocks @Autowired CreateMailboxService mCreateMailboxService; @Before public void setup() { MockitoAnnotations.initMocks(this); } @Test public void deleteWithPermission() { when(mUserInfoService.getData()).thenReturn("mocked text"); System.out.println("test 1: " + mUserInfoService.getData()); mCreateMailboxService.createMailbox(); } }
但结果会如此
test 1: mocked text test 2: original text // I want this be "mocked text", too
似乎CreateMailboxService 没有得到模拟的UserInfoService,而是使用Spring的自动装配bean.为什么我@InjectMocks
不工作?
问候