不推荐使用MockitoJUnitRunner


68

我正在尝试使用@InjectMocks和进行单元测试@Mock

@RunWith(MockitoJUnitRunner.class)
public class ProblemDefinitionTest {

    @InjectMocks
    ProblemDefinition problemDefinition;

    @Mock
    Matrix matrixMock;    

    @Test
    public void sanityCheck() {
        Assert.assertNotNull(problemDefinition);
        Assert.assertNotNull(matrixMock);
    }
}

当我不包含@RunWith注释时,测试将失败。但

不推荐使用MockitoJUnitRunner类型

我正在使用Mockito 2.6.9。我应该怎么做?

Answers:



10

您可以尝试以下方法:

@Before
public void setup() {
    MockitoAnnotations.initMocks(this);
}

由于添加了@Before注释,因此模拟对象可以是新的,并且可以记录多次,并且在所有测试中,您都可以为对象赋予新的属性。但是,如果您想一次记录模拟对象的行为,请添加@BeforeCLass


5

还有一个@Rule选项:

@Rule 
public MockitoRule rule = MockitoJUnit.rule();

或在科特林:

@get:Rule
var rule = MockitoJUnit.rule()


0

在我将依赖项更新为最新版本的情况下,我设法解决了这一问题:

def mockito_version = '2.28.2'

// For local unit tests on your development machine
testImplementation "org.mockito:mockito-core:$mockito_version"

// For instrumentation tests on Android devices and emulators
androidTestImplementation "org.mockito:mockito-android:$mockito_version"

然后,通过替换命令(Mac:cmd + Shift + R Windows:Ctrl + Shift + R)从

import org.mockito.runners.MockitoJUnitRunner; 

import org.mockito.junit.MockitoJUnitRunner;

-2

如果您不想使用@RunWith(MockitoJUnitRunner.class),可以尝试一下

@BeforeClass
public void setup() {
    MockitoAnnotations.initMocks(this);
}

1
“ BeforeClass”方法应该是静态的,并且不能访问“ this”
Maxple
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.