Java – how do you simulate output streams?

By 'output steam' I mean any object that receives a sequence of bytes or any character So, Java io. OutputStream, and Java io. Writer,javax. xml. stream. The writecharacters method of xmlstreamwriter, and so on

I'm writing simulation based tests for a class whose main function is to write data streams to one of them (xmlstreamwriter, because it happens)

The problem is that the data stream writes a series of calls to the write method, but the important thing is not the call, but the data For example, give an xmlstreamwriter, which:

out.writeCharacters("Hello,");
out.writeCharacters("world!");

Equivalent to this:

out.writeCharacters("Hello,world!");

It really doesn't matter (for my purpose) to happen There will be some specific call order, but I don't care what it is, so I don't want to write the expectation of this specific order I just want to be able to write a certain amount of data in some way

One option is to switch to state - based testing I can accumulate data in the buffer and assert it However, since I'm writing XML, this means making some complex and ugly assertions Ridicule seems to be a better way to deal with the larger problem of writing XML

So how do I use this simulation?

I use moxie ridicule, but I'm interested in hearing any way to ridicule the library

Solution

A fairly elegant strategy for testing an output or input stream is to use the pipedinputstream and pipedoutputstream classes You can wire them together in the setup of the test, and then check the content after executing the target method

You can prepare some input from another direction, and then let the test read the prepared data from the input stream

In your case, you can use pipedoutputstream to simulate the "out" variable and insert pipedinputstream in the following way:

private BufferedReader reader;

@Before
public void init() throws IOException {
    PipedInputStream pipeInput = new PipedInputStream();
    reader = new BufferedReader(
            new InputStreamReader(pipeInput));
    bufferedoutputstream out = new bufferedoutputstream(
            new PipedOutputStream(pipeInput))));
    //Here you will have to mock the output somehow inside your 
    //target object.
    targetObject.setOutputStream (out);
    }


@Test
public test() {
    //Invoke the target method
    targetObject.targetmethod();

    //Check that the correct data has been written correctly in 
    //the output stream reading it from the plugged input stream
    Assert.assertEquals("something you expects",reader.readLine());
    }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>