hi.
I tried to use this to be able to run mockito and spring together in my test.
but I can not use the @injectMock annotation on a field annotated with @Resource.
I get an exception: that I didn't provide instance for that field, but spring should do it for me because I annotate this with @Resource.
Any suggestions how to avoid it? I want to use interfaces and not classes and I want spring to initialize my bean, and I also want to use the annotation @injectMocks.
that is the exception:
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'userService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
let's see the example:
I have UserService interface:
public interface UserService {
public int addUser(User user) ;}
and class:
@Service
public class UserServiceImpl implements UserService{
@Resource
private UserDao userDao;
@Override
public int addUser(User user) {
User existingUser = userDao.findByName(user.getName());
if (existingUser != null) {
throw new Exception ...
}
Integer id = userDao.create(user);
return id;
}
}
@ContextConfiguration(locations = {....})
@RunWith(MockitoJUnitRunner.class)
public class SpringMockTest {
@ClassRule
public static final SpringClassRule SPRING_CLASS_RULE = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
@InjectMocks @Resource
private UserService userService;
@Mock
private UserDao userDao;
@Test
public void testMockito() {
Mockito.when(userDao.findByName("bla")).thenReturn(null);
Mockito.when(userDao.create(Mockito.any(User.class))).thenReturn(1);
int id = userService.addUser(new User("bla", "bla"));
Assert.assertEquals(1, id);
Mockito.reset(userDao);
}
}