【发布时间】:2017-05-25 20:45:23
【问题描述】:
我正在使用 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 不起作用?
【问题讨论】:
-
如果你想模拟它们,我认为你需要 MockitoJunitRunner.class。还可以使用 when() 存根来模拟用于 mUserInfoService 的函数。
-
将 mock 注册为 spring bean。您现在只会从上下文中接收 bean,它不会模拟任何东西(如您所见)。
标签: java spring unit-testing mockito