用 Mockito 注入模拟不起作用
2022-09-05 00:01:42
我正在使用Mockito来测试我的Spring项目,但是将模拟服务注入到另一个Spring服务(bean)中似乎不起作用。@InjectMocks
以下是我想测试的春季服务:
@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