如何使用PrintWriter测试方法? [英] How to test a method using a PrintWriter?
问题描述
我有以下方法:
@Component
public class WriteCsvToResponse {
private static final Logger LOGGER = LoggerFactory.getLogger(WriteCsvToResponse.class);
public void writeStatus(PrintWriter writer, Status status) {
try {
ColumnPositionMappingStrategy mapStrategy
= new ColumnPositionMappingStrategy();
mapStrategy.setType(Status.class);
String[] columns = new String[]{"id", "storeId", "status"};
mapStrategy.setColumnMapping(columns);
StatefulBeanToCsv btcsv = new StatefulBeanToCsvBuilder(writer)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.withMappingStrategy(mapStrategy)
.withSeparator(',')
.build();
btcsv.write(status);
} catch (CsvException ex) {
LOGGER.error("Error mapping Bean to CSV", ex);
}
}
我不知道如何使用 mockito
。
使用它可以将对象状态包装为 csv
格式。
我使用StringWriter将响应包装在其中。
没有更多细节了,但是看来我必须创建一些字词才能通过验证:)
Use it to wrap the object status into csv
format.
I used StringWriter to wrap the response in it.
There are no more details left, but it seems I have to create some words to pass the validation :)
推荐答案
您不需要mockito来测试此方法,只需一个 java.io.StringWriter
。
You do not need mockito to test this method, only a java.io.StringWriter
.
这里是您可以针对名义用途编写测试:
Here is how you can write the test for a nominal use:
@Test
void status_written_in_csv_format() {
// Setup
WriteCsvToResponse objectUnderTest = new WriteCsvToResponse ();
StringWriter stringWriter = new StringWriter();
PrintWriter printWriter = new PrintWriter(stringWriter);
// Given
Status status = ...
// When
objectUnderTest.writeStatus(printWriter, status);
// Then
String actualCsv = stringWriter.toString();
assertThat(actualCsv.split("\n"))
.as("Produced CSV")
.containsExactly(
"id,storeId,status",
"42,142,OK");
}
此示例假设您的状态有一些事情
对象,但是您有基本的想法。
对于断言,我使用 AssertJ ,但是您可以使用内置的JUnit5进行相同的操作-in断言。
This example assume some things about your Status
object, but you have the general idea.
For assertions, I use AssertJ, but you can do the same with JUnit5 built-in assertions.
希望这会有所帮助!
这篇关于如何使用PrintWriter测试方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!