gpt4 book ai didi

java - 模拟无法为测试用例生成文本文件

转载 作者:行者123 更新时间:2023-12-01 16:25:40 25 4
gpt4 key购买 nike

我正在创建模拟来检查记录器功能。为此,我有接口(interface)并为此创建模拟。但它不起作用。任何帮助表示赞赏。

这是我的界面

public interface ILoggerMock {

public void write(String text) throws Throwable;
}

这是我的测试课

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.List;

import org.junit.Test;
import org.mockito.Mockito;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

public class LoggerMock {

@Test
public void out() throws Throwable {

ILoggerMock iLoggerMock = Mockito.mock(ILoggerMock.class);

Mockito.doAnswer(new Answer<Void>() {
public Void answer(InvocationOnMock invocationOnMock) throws Throwable, IOException {
try {
System.out.println("CalculatorMock.out().new Answer() {...}.answer()");

Files.write(Paths.get("D:/log/logger.txt"), "Hello!".getBytes(), StandardOpenOption.CREATE);
} catch (IOException e) {
// exception handling
}
return null;
}
}).when(iLoggerMock).write("write");

List<String> list = Files.readAllLines(Paths.get("D:/log/logger.txt"));

for (String line : list) {
System.out.println(line);
}

//System.out.print("hello");
assertEquals("Hello!", list.get(0));
}

}

问题出在模拟中,我无法创建文件。请帮助我创建文件。

最佳答案

首先请参阅Is “throws Throwable” good practice关于您的接口(interface)声明。

@BeUndead在问题的评论中提到所有 Mockito 方法与 when(...) 结合使用,只需准备一个模拟,当稍后调用其方法之一时要做什么。

代码中的

Mockito.doAnswer(...).when(iLoggerMock).write("write"); 定义了模拟 write() 后执行的操作使用参数“write”调用方法。因此,要真正使事情发生,您必须在之后的某个地方调用 iLoggerMock.write("write") 。 (但是 write 并不是您想要写入的文本,它是 Hello!。)

工作代码可能如下所示:

主类

public interface ILogger {

public void write( String text ) throws Exception;

public Path getLog();
}

测试类

abstract class AbstractLoggerTest {

protected Path log;

protected void testWrite( ILogger logger, String text ) throws Exception {

log = logger.getLog(); // here happens what has been prepared in when(...).thenReturn(...); below

logger.write( text ); // here happens what has been prepared in doAnswer(...).when(...).write(...); below

assertEquals( "Wrong line count", 1,
Files.lines( log )
.map( line -> {
//System.out.println( line ); // Uncomment this if you really must.
// Actually we are using automated tests for this:
// To prevent having to trace program or test outputs manually.
assertEquals( "Written and read text not equal", text, line );
return line;
} ).count() );
}

protected String textToWrite( ILogger forLogger, Path toLog ) {

return String.format( "Text from %s written to %s.",
forLogger.getClass().getName(), toLog );
}
}
public class ILoggerTest extends AbstractLoggerTest {

private static final String LOG_FILE = "target/interface.log.txt";

@Mock
private ILogger logger;

@Before
public void before() {

MockitoAnnotations.initMocks( this );
log = Paths.get( LOG_FILE );
when( logger.getLog() ).thenReturn( LOG ); // this prepares the mock what to do when `logger.getLog()` is invoked later
}

@Test
public void testWrite() throws Exception {

final String TEXT_TO_WRITE = textToWrite( logger, log );

doAnswer( new Answer<Void>() {

@Override
public Void answer( InvocationOnMock invocation ) throws IOException {

Object[] args = invocation.getArguments();
Files.writeString( log, (String) args[0] );
return null;
}
} ).when( logger ).write( any() ); // this prepares the mock what to do when `logger.write()` is invoked
// with any argument later (String, in this case. The argument type
// will get inferred by the compiler.)


testWrite( logger, TEXT_TO_WRITE );
verify( logger ).write( TEXT_TO_WRITE );
}
}

AbstractLoggerTest 类的优点是,如果将来创建 ILogger 实现[为简洁起见,省略了构造函数和 setters/getters]:

主要类

public abstract class AbstractLogger implements ILogger {

protected Path log;

@Override
public void write( String text ) throws IOException {

Files.writeString( log, text );
}

@Override
public Path getLog() {

return log;
}
}
public class TextLogger extends AbstractLogger {

{
log = Paths.get( "target/log.txt" );
}
}

它的测试类看起来就像:

public class TextLoggerTest extends AbstractLoggerTest {

@Test
public void testWrite() throws Exception {

ILogger logger = new TextLogger();
testWrite( logger, textToWrite( logger, logger.getLog() ) );
}
}

关于java - 模拟无法为测试用例生成文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62154784/

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