gpt4 book ai didi

java - 想要但未调用 : Mockito PrintWriter

转载 作者:行者123 更新时间:2023-11-30 07:05:42 24 4
gpt4 key购买 nike

您好,我正在开发一个项目,并使用 PrintWriter 类打开和写入文件。但是当我编写相同的测试用例时,它在第 153 行给出以下错误

Wanted but not invoked:
mockPrintWriter.println("ID url1
");
-> at x.y.z.verify(ProcessImageDataTest.java:153)
Actually, there were zero interactions with this mock.

代码:(使用Lombok库)

ProcessImageData.java

@Setter
@RequiredArgsConstructor
public class ProcessImageData implements T {
private final File newImageDataTextFile;

@Override
public void execute() {
LineIterator inputFileIterator = null;
try {
File filteredImageDataTextFile = new File(filteredImageDataTextFilepath);

PrintWriter writer = new PrintWriter(newImageDataTextFile);
inputFileIterator = FileUtils.lineIterator(filteredImageDataTextFile, StandardCharsets.UTF_8.displayName());
while (inputFileIterator.hasNext()) {
if(someCondition)
**Line51** writer.println(imageDataFileLine);
//FileUtils.writeStringToFile(newImageDataTextFile, imageDataFileLine + NEWLINE, true);
}
}

} catch (Exception e) {

} finally {
LineIterator.closeQuietly(inputFileIterator);
**LINE63** writer.close();
}
}

ProcessImageDataTest.java

@RunWith(PowerMockRunner.class)
@PrepareForTest({ ProcessImageData.class, FileUtils.class, Printwriter.class })
public class ProcessImageDataTest {

private ProcessImageData processImageData;

private static final String FILTERED_IMAGE_DATA_TEXT_FILE_PATH = "filteredFilepath";
private File FILTEREDFILE = new File(FILTERED_PATH);
private static final File IMAGE__FILE = new File("imageFilePath");

private LineIterator lineIterator;
@Mock
private PrintWriter mockPrintWriter;

@Before
public void init() throws Exception {
MockitoAnnotations.initMocks(this);

processImageData = new ProcessImageData(Palettes_file, FILTERED_PATH, IMAGE_FILE);

PowerMockito.mockStatic(FileUtils.class);
PowerMockito.whenNew(PrintWriter.class).withArguments(IMAGE_FILE).thenReturn(mockPrintWriter);

PowerMockito.when(FileUtils.lineIterator(FILTERED_FILE, StandardCharsets.UTF_8.displayName())).thenReturn(lineIterator);
PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);

}

@Test
public void testTaskWhenIDInDBAndStale() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID1 + SPACE + URL2);

processImageData.execute();

List<String> exepctedFileContentOutput = Arrays.asList(ID2 + SPACE + URL1 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}


@Test
public void testTaskWhenIDNotInDB() throws IOException {
PowerMockito.when(lineIterator.nextLine()).thenReturn(ID2 + SPACE + URL1, ID3 + SPACE + URL2);

processImageData.execute();

List<String> exepctedFileContentOutput = Arrays.asList(ID3 + SPACE + URL2 + NEWLINE);
verify(exepctedFileContentOutput, 1, 1);
}

private void verify(List<String> exepctedFileContentOutput, int fileWriteTimes, int fileReadTimes) throws IOException {
for (String line : exepctedFileContentOutput){
**Line153** Mockito.verify(mockPrintWriter, Mockito.times(fileWriteTimes)).print(line);
}

PowerMockito.verifyStatic(Mockito.times(fileReadTimes));
FileUtils.lineIterator(FILTERED_IMAGE_DATA_TEXT_FILE, StandardCharsets.UTF_8.displayName());
}

}

我还模拟了 PrintWriter 的一个新运算符,使用 bean 注入(inject)。我做错了什么?我坚持了很长时间却没有收到错误?如有任何帮助,我们将不胜感激。

更新:

我做了下面建议的更改并更新了代码,但现在我收到错误:

Wanted but not invoked: mockPrintWriter.print("ASIN2 url1 "); -> 
at softlines.ctl.ruleExecutor.tasks.ProcessImageDataTest.verify‌​(ProcessImageDataTes‌​t.java:153)
However, there were other interactions with this mock: -> at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​51) ->
at softlines.ctl.ruleExecutor.tasks.ProcessImageData.execute(Pr‌​ocessImageData.java:‌​58) –

最佳答案

我在您的测试中发现 3 个问题:

  1. 您不会尝试模拟正确的构造函数,实际上,在execute方法中,您仅使用创建您的PrintWriter当您尝试模拟具有 2 个参数的构造函数时,一个参数为 File 类型,其中一个参数为 File 类型,另一个参数为 File 类型字符串

所以代码应该是:

PowerMockito.whenNew(PrintWriter.class)
.withArguments(IMAGE_FILE)
.thenReturn(mockPrintWriter);
  • 为了能够模拟构造函数,您需要准备创建实例的类,在本例中为 ProcessImageData,因此您需要添加 ProcessImageData.class > 在注释@PrepareForTest中。 (我不确定那里是否需要 ProcessImageDataTest.class)

  • 字段lineIterator应使用@Mock进行注释。

  • 您应该直接验证 println 不使用新行,而不是使用新行验证 print ,这样更不容易出错.

  • <小时/>

    我简化了你的代码来展示这个想法。

    假设ProcessImageData是:

    public class ProcessImageData {

    private final File newImageDataTextFile;

    public ProcessImageData(final File newImageDataTextFile) {
    this.newImageDataTextFile = newImageDataTextFile;
    }

    public void execute() throws Exception{
    try (PrintWriter writer = new PrintWriter(newImageDataTextFile)) {
    LineIterator inputFileIterator = FileUtils.lineIterator(
    newImageDataTextFile, StandardCharsets.UTF_8.displayName()
    );
    while (inputFileIterator.hasNext()) {
    writer.println(inputFileIterator.nextLine());
    }
    }
    }
    }

    我的单元测试将是:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({ProcessImageData.class, FileUtils.class})
    public class ProcessImageDataTest {

    private File file = new File("imageFilePath");

    private ProcessImageData processImageData;
    @Mock
    private PrintWriter mockPrintWriter;
    @Mock
    private LineIterator lineIterator;

    @Before
    public void init() throws Exception {
    MockitoAnnotations.initMocks(this);

    processImageData = new ProcessImageData(file);
    PowerMockito.whenNew(PrintWriter.class)
    .withArguments(file)
    .thenReturn(mockPrintWriter);
    PowerMockito.mockStatic(FileUtils.class);
    PowerMockito.when(
    FileUtils.lineIterator(file, StandardCharsets.UTF_8.displayName())
    ).thenReturn(lineIterator);
    PowerMockito.when(lineIterator.hasNext()).thenReturn(true, true, false);
    }

    @Test
    public void testExecute() throws Exception {
    PowerMockito.when(lineIterator.nextLine()).thenReturn("Foo", "Bar");
    processImageData.execute();
    Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Foo");
    Mockito.verify(mockPrintWriter, Mockito.times(1)).println("Bar");
    }
    }

    更多详情请参阅How to mock construction of new objects .

    <小时/>

    how can I add verification in unit test for writer.close?

    一种方法可能是通过将下一行添加到单元测试中来简单地检查 close() 是否被调用:

    Mockito.verify(mockPrintWriter,  Mockito.times(1)).close();

    关于java - 想要但未调用 : Mockito PrintWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40173392/

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