gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 03:41:43 24 4
gpt4 key购买 nike

我在没有 @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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com