How to inject a mock object to a class when testing?

前端 未结 2 1380
無奈伤痛
無奈伤痛 2021-01-14 19:11

My user class is as follows,

public class UserResource {
  @Inject UserService userService;

  public boolean createUser(User user) {
    DbResponse res          


        
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-14 19:18

    Although I completely support the answer of @Nkosi I'd like to add this for completeness:

    Use Mockitos JUnitRule to reate the mocks as described here: http://www.vogella.com/tutorials/Mockito/article.html :

    public class UserResourceTest {
        @Rule 
        public MockitoRule mockitoRule = MockitoJUnit.rule(); 
        @Mock
        private  DbResponse mockResponse;
        @Mock
        private UserService mockService;    
    
        @Test
        public void test() {
            //Arrange
            boolean expected = true; 
            when(mockResponse.isSuccess).thenReturn(expected);
            when(mockService.addUser(user)).thenReturn(mockResponse);
            // ...
    

    Also then you could also use Mockitos @InjectMocks annotation like this:

    public class UserResourceTest {
        @Rule 
        public MockitoRule mockitoRule = MockitoJUnit.rule(); 
        @Mock
        private  DbResponse mockResponse;
        @Mock
        private UserService mockService;
        @InjectMocks
        private UserResource userResource; // do not instantiate in test method
         // ...
    

    But I personally would discourage from it.

    Yes, it is more convenient since it determines by reflection which dependency injection method you use. But if you don't have a "seam" to inject a certain dependency (neither Costructor parameter, non final property nor setter of matching type) you don't get a compile error which I personally find problematic.

提交回复
热议问题