java - 为什么 Mockito 模拟在没有注释的情况下在我的测试中工作

标签 java junit mocking mockito

我在没有 @RunWithinitMocks() 的情况下运行测试。不是应该不行吗?

public class MultiFilesIteratorInMemoryTest {
    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void getNextLine() throws Exception {

    }

    @Test
    public void timeFrameIsSplitIntoTwoFilesReturnAllRelevantRecords() throws Exception {

        IRandomAccess randomAccessFile1 = mock(RandomAccessFileWrapper.class);
        IRandomAccess randomAccessFile2 = mock(RandomAccessFileWrapper.class);
        IFileUtils fileUtils = mock(FileUtils.class);

        when(randomAccessFile1.readLine()).thenReturn("first file content").thenReturn(null);
        when(randomAccessFile2.readLine()).thenReturn("second file content").thenReturn(null);
        when(fileUtils.getCountOfSimilarNamedFilesFromDir(anyString())).thenReturn(2);

        IMultiFilesMerger multiFilesMerger = new MultiFilesIteratorInMemory(fileUtils, ImmutableList.of(randomAccessFile1, randomAccessFile2));


        String nextLine = multiFilesMerger.getNextLine();
        assertThat(nextLine, equalTo("first file content"));
        nextLine = multiFilesMerger.getNextLine();
        assertThat(nextLine, equalTo("second file content"));
    }
}

最佳答案

不,它会工作得很好,因为您是显式创建模拟并且它们不会被注入(inject)。

MockitoJUnitRunner仅用于注入(inject)用 @Mock 注解的模拟:

Initializes mocks annotated with Mock, so that explicit usage of MockitoAnnotations.initMocks(Object) is not necessary.

initMocks 也是如此:

MockitoAnnotations.initMocks(this); initializes fields annotated with Mockito annotations.

在您的代码中,您没有将 Mockito 带注释的字段与 @Mock@InjectMocks 一起使用。相反,您使用 mock 显式创建模拟。静态工厂。

关于java - 为什么 Mockito 模拟在没有注释的情况下在我的测试中工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36772226/

相关文章:

java - 生产者/消费者场景中的双向流

java - 使用 GSON 不解析字段,只保留它与 json 原始字符串

javascript - 使用 WebView 获取 android 的 JavaScript 值

python - 如何仅在测试类而不是单元测试用例中模拟函数

mocking - Jest 模拟全局 navigator.onLine

java - 结合 Ant 和 Maven 项目

java - 有没有办法跟踪 JUnit 中多个断言测试用例的每个断言?

java - 静态字段的 JUnit 初始化

java - 如何使用 JUNIT 超越或跳过某个方法?

reactjs - 如何对 apollo 链接进行单元测试