問題描述
我目前正在研究 Mockito 框架,并使用 Mockito 創建了幾個測試用例.但后來我讀到,我可以使用 @Mock
和 @InjectMocks
而不是調用 mock(SomeClass.class) - 我唯一的需要做的是用 @RunWith(MockitoJUnitRunner.class)
注釋我的測試類或使用 MockitoAnnotations.initMocks(this);
在 @Before代碼>方法.
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 can use the @Mock
and the @InjectMocks
- The only thing I need to do is to annotate my test class with @RunWith(MockitoJUnitRunner.class)
or use the MockitoAnnotations.initMocks(this);
in the @Before
method.
但它不起作用 - @Mock
似乎不起作用!這是我的 2 個代碼修訂版 - 一個使用注釋,一個沒有.
But it doesn't work - It seems that the @Mock
won't work!
Here is my 2 codes revisions - one using the annotations and one without.
我做錯了什么?
public class ReportServiceImplTestMockito {
private TaskService mockTaskService; // This is the Mock object
private ReportServiceImpl service;
@Before
public void init(){
service = new ReportServiceImpl();
mockTaskService = mock(TaskServiceImpl.class);
service.setTaskServiceImpl(mockTaskService);
}
/// ...
Some tests
}
正如我所說 - 這工作很棒.但以下不會:
As I said - this work great. But the following wont:
@RunWith(MockitoJUnitRunner.class)
public class ReportServiceImplTestMockito {
@Mock
private TaskService mockTaskService;
@InjectMocks
private ReportServiceImpl service;
// Some tests
}
這里是 ReportServiceImpl
類:
@Service
public class ReportServiceImpl implements ReportService {
@Autowired
private TaskService taskServiceImpl;
public ReportServiceImpl(){}
public ReportServiceImpl(TaskService taskService){
this.taskServiceImpl = taskService;
}
public void setTaskServiceImpl(TaskService taskServiceImpl) {
this.taskServiceImpl = taskServiceImpl;
}
}
我錯過了什么?
推薦答案
好吧,我搞錯了!!!我使用了 @InjectMocks
但在 init() 方法中初始化了相同的變量...所以發生的事情是,mockito 將模擬對象注入到我的變量中 - 但幾秒鐘后我運行了它 - 初始化了同一個變量!!!
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!!!
這篇關于使用@Mock 和@InjectMocks的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!