我正在使用 Mockito 测试我的 Spring 项目,但是 @InjectMocks
似乎无法将模拟服务注入(inject)另一个 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 的 Autowiring bean。
为什么我的 @InjectMocks
不工作?
最佳答案
就我而言,我在使用 JUnit5 时遇到了类似的问题
@ExtendWith(MockitoExtension.class)
class MyServiceTest {
...
@InjectMocks
MyService underTest;
@Test
void myMethodTest() {
...
}
underTest
为空。
问题的原因是我使用了 JUnit4 包 import org.junit.Test;
中的 @Test
而不是 JUnit5 import org.junit.jupiter.api.Test ;
关于java - 用 Mockito 注入(inject)模拟不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41584454/