問題描述
我看到我認為是錯誤的行為.@InjectMocks 似乎并沒有在每個測試方法之前創建一個新的測試主題.@Mock 在哪里.在以下示例中,如果 Subject.section 是最后一個 @Test 失敗.如果它不是最終的,則兩者都通過.我目前的解決方法是使用@BeforeClass,但這并不理想.
I am seeing behaviour that I believe is a bug. @InjectMocks does not seem to create a new test subject before every test method. Where as @Mock does. In the following example, if Subject.section is final one @Test fails. If its not final both pass. My current workaround is to use @BeforeClass, but this is not ideal.
主題.java:
package inject_mocks_test;
public class Subject {
private final Section section;
public Subject(Section section) {
this.section = section;
}
public Section getSection() {
return section;
}
}
Section.java:
Section.java:
package inject_mocks_test;
public class Section {}
SubjectTest.java
SubjectTest.java
package inject_mocks_test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.testng.Assert.assertEquals;
public class SubjectTest {
@Mock
Section section;
@InjectMocks
Subject subject;
@BeforeMethod
public void setup() {
MockitoAnnotations.initMocks(this);
}
@Test
public void test1() {
assertEquals(section, subject.getSection());
}
@Test
public void test2() {
assertEquals(section, subject.getSection());
}
}
干杯.
推薦答案
您正在使用 @InjectMocks
進行 constructor 注入.只要 Mockito 找到未初始化的字段(空),這將起作用.JUnit 在每次測試之前都會創建一個新的測試類實例,所以 JUnit 粉絲(像我一樣)永遠不會遇到這樣的問題.TestNg 沒有創建測試類的新實例.它保持測試方法之間的狀態,所以當 MockitoAnnotations.initMocks(this)
第二次調用時,Mockito 會發現 subject 字段已經初始化并嘗試使用 <強>場注入.這在另一回合將一直有效,直到該領域不是最終的.
You are using the @InjectMocks
for constructor incjection. This will work as long as Mockito finds the field not initalized (null). JUnit is creating a new instance of the test class before each test, so JUnit fans (like me) will never face such problem. TestNg is not creating a new instance of test class. It's keeping the state between test methods, so when MockitoAnnotations.initMocks(this)
is called for the second time, Mockito will find subject field already initialized and will try to use field injection. This on the other turn will work until the field is not final.
這是一個錯誤嗎?我相信不是——而是 API 設計的自然結果.一些解決方法是添加
Is this is a bug? I believe not - rather a natural consequence of the API design. Some workaround for you would be to add
this.subject = null;
在一些 @AfterMethod
方法中.
這篇關于Mockito,@InjectMocks 最終字段的奇怪行為的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!