Using @Mock and @InjectMocks

后端 未结 3 1429
旧巷少年郎
旧巷少年郎 2020-12-06 03:55

I\'m currently studying the Mockito framework and I\'ve created several test cases using Mockito. But then I read that instead of invoking mock(SomeClass.class) I c

相关标签:
3条回答
  • 2020-12-06 04:19

    O.K, I got my mistake!!! I've used the @InjectMocks but initialized the same variable in the init() method... So what happened was that mockito injected the mock objects to my variable - but seconds later I ran it over - initializing that very same variable!!!

    0 讨论(0)
  • 2020-12-06 04:21

    Your code works fine for me using Mockito 1.9.

    Using an 1.8+ version of Mockito I get a very specific error message telling me exactly how to fix the problem. As php-coder suggests: For Mockito 1.8+ you need to initialize the field.

    Did you see this or any other error message?

    Edit:

    The following code works for me. Small changes:

    • Removed Spring annotations
    • Removed Interface
    • Added Getter
    • Added empty TaskService
    • Added test with System.out.println

    Does it produce an error for you? :

    Service:

    public class ReportServiceImpl {
    
        private TaskService taskServiceImpl;
    
    
        public ReportServiceImpl() {
    
        }
    
    
        public ReportServiceImpl(TaskService taskService) {
            this.taskServiceImpl = taskService;
        }
    
    
        public void setTaskServiceImpl(TaskService taskServiceImpl) {
            this.taskServiceImpl = taskServiceImpl;
        }
    
    
        public TaskService getTaskServiceImpl() {
            return taskServiceImpl;
        }
    }
    

    Dependency:

    public class TaskService {
    
    }
    

    Test, prints mockTaskService:

    @RunWith(MockitoJUnitRunner.class)
    public class ReportServiceImplTestMockito {
    
        @Mock
        private TaskService       mockTaskService;
    
        @InjectMocks
        private ReportServiceImpl service;
    
    
        @Test
        public void testMockInjected() {
            System.out.println(service.getTaskServiceImpl());
        }
    }
    
    0 讨论(0)
  • 2020-12-06 04:43

    I'm not sure, but try to create new instance of ReportServiceImpl manually (as you did in working example):

     @InjectMocks 
     private ReportServiceImpl service = new ReportServiceImpl();
    
    0 讨论(0)
提交回复
热议问题