Spring JUnit Rules and MockitoJUnitRunner

2,159 views
Skip to first unread message

brachi packter

unread,
Feb 22, 2016, 4:29:49 AM2/22/16
to mockito
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;
}
}


 and test class:
@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);


}
}

Артур Загретдинов

unread,
Feb 22, 2016, 5:41:48 AM2/22/16
to mockito
Hello,

Easiest way to answer your question it’s create sample. So I did it. 


In your code when Mockito runs and apples rules, Spring don’t start and inject ‘Resource’, so field still null. If you want to Mockito with Spring Integration testing you need manually create mocks for beans and then let Spring do it job - injecting dependency . Inject dependency not only in production code, but also in test classes.  

Best regrads,
Arthur Zagretdinov

понедельник, 22 февраля 2016 г., 12:29:49 UTC+3 пользователь brachi packter написал:
Reply all
Reply to author
Forward
0 new messages