How to test a method using a PrintWriter?

放肆的年华 提交于 2020-01-15 09:23:26

问题


I have following method:

@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);
        }
    }

I have no idea how to test it properly using mockito.

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 :)


回答1:


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");
}

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.

Hope this helps !




回答2:


With a bit of a refactoring, where the Builder is a Spring Bean injected into this component.

You can then mock that builder to return a mocked StatefulBeanToCsv, specifically the write method, where you write the conditions and assertions. If you encounter an error, you throw some unchecked exception, like IllegalStateException, if everything is alright, you don't throw anything




回答3:


you can write a test like this and change your input in write method:

    @Test
    public void test() {
        WriteCsvToResponse writeCsvToResponse = mock(WriteCsvToResponse.class);

        doAnswer(new Answer() {
            public Object answer(InvocationOnMock invocation) {
                Object[] args = invocation.getArguments();
                write((Status)args[1]);
                return null;
            }
        }).when(writeCsvToResponse).writeStatus(any(PrintWriter.class),any(Status.class));

        writeCsvToResponse.writeStatus(writer, status);
    }

    public void write(Status status) {
//      do anythings you like with status
    }


来源:https://stackoverflow.com/questions/52274976/how-to-test-a-method-using-a-printwriter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!