Mockito 模拟如何在没有注释的情况下在我的测试中工作

How come Mockito mocks worked in my tests without annotation

我 运行 我的测试没有 @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"));
    }
}

不,它会工作得很好,因为你明确地创建了你的模拟并且它们没有被注入。

MockitoJUnitRunner 仅用于注入注释为 @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.

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