Mockito,@ InjectMocks与最终字段的奇怪行为

use*_*457 11 java testng mockito

我看到的行为我认为是一个错误.@InjectMocks似乎在每个测试方法之前都没有创建新的测试主题.@Mock的地方.在以下示例中,如果Subject.section是最终的,则@Test失败.如果它不是最后都通过.我目前的解决方法是使用@BeforeClass,但这并不理想.

Subject.java:

package inject_mocks_test;
public class Subject {

    private final Section section;

    public Subject(Section section) {
        this.section = section;
    }

    public Section getSection() {
        return section;
    }
}
Run Code Online (Sandbox Code Playgroud)

Section.java:

package inject_mocks_test;

public class Section {}
Run Code Online (Sandbox Code Playgroud)

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());        
    }
}
Run Code Online (Sandbox Code Playgroud)

干杯.

mac*_*ias 24

您正在使用@InjectMocksfor 构造函数注入.只要Mockito发现该字段未被初始化(null),这将起作用.JUnit在每次测试之前都会创建一个测试类的新实例,所以JUnit粉丝(像我一样)永远不会遇到这样的问题.TestNg没有创建测试类的新实例.它保持测试方法之间的状态,因此当MockitoAnnotations.initMocks(this)第二次调用时,Mockito将发现主题字段已经初始化并将尝试使用字段注入.另一方面,这将是有效的,直到该领域不是最终的.

这是一个错误吗?我不相信 - 而是API设计的自然结果.您可以添加一些解决方法

this.subject = null;
Run Code Online (Sandbox Code Playgroud)

在某种@AfterMethod方法.