I'm using Mockito to test my Spring project, but the @InjectMocks
seems not working in injecting a mocked service into another Spring service(bean).
Here is my Spring service that I want to test:
@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());
}
}
And below is the service that I want to mock:
@Service
public class UserInfoService {
public String getData() {
return "original text";
}
}
My test code is here:
@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();
}
}
but the result would like
test 1: mocked text
test 2: original text // I want this be "mocked text", too
it seems that the CreateMailboxService didn't get the mocked UserInfoService but using Spring's autowired bean.
Why is my @InjectMocks
not working?