模拟 Java InputStream

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6371379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:25:20  来源:igfitidea点击:

Mocking Java InputStream

javamocking

提问by Reji

Please provide pointers to help me mock that java InputStream object. This is the line of code that I would wish to Mock:

请提供指针以帮助我模拟该 java InputStream 对象。这是我希望模拟的代码行:

InputStreamReader inputData = new InputStreamReader(System.in);
bufferdReader = new BufferedReader(inputData);
bufferdReader.readLine(); 

采纳答案by Boris Pavlovi?

BufferedReader bufferedReader = org.mockito.Mockito.mock(BufferedReader.class);
when(bufferedReader.readLine())
  .thenReturn("first line")
  .thenReturn("second line");

org.junit.Assert.when(new Client(bufferedReader).parseLine())
  .thenEquals(IsEqual.equalTo("first line"));

回答by pap

You could just use a ByteArrayInputStreamand fill it with your test data.

您可以使用 aByteArrayInputStream并用您的测试数据填充它。

@Brad's example from the comments:

评论中的@Brad 示例:

InputStream anyInputStream = new ByteArrayInputStream("test data".getBytes());

回答by Eric

You could use commons-ioto create some stub input streams:

您可以使用commons-io创建一些存根输入流:

InputStream stubInputStream = 
     IOUtils.toInputStream("some test data for my input stream", "UTF-8");

回答by Nathan Hughes

Change your object so it is easier to test, something like this:

更改您的对象,以便更容易测试,如下所示:

public MyObject {
    private InputStream inputStream;

    public void setInputStream(InputStream inputStream) {this.inputStream = inputStream;}

    public void whatever() {
        InputStreamReader inputData = new InputStreamReader(inputStream);
        bufferdReader = new BufferedReader(inputData);
        bufferdReader.readLine(); 
    }
}

then when you use your object initialize its inputStream first:

然后当你使用你的对象时,首先初始化它的 inputStream:

MyObject myObject = new MyObject();
myObject.setInputStream(System.in);

Now you have an object where you can test it using any implementation of InputStream you want (ByteArrayInputStream is a good one to try).

现在您有了一个对象,您可以在其中使用您想要的 InputStream 的任何实现来测试它(ByteArrayInputStream 是一个很好的尝试)。

回答by John Deverall

I disagree with the selected answer for this question. Mocking frameworks like Mockito are nice and all, however when standard java api is available you might consider using that instead.

我不同意这个问题的选定答案。像 Mockito 这样的模拟框架很好,但是当标准 java api 可用时,您可能会考虑使用它。

i.e.

IE

BufferedReader reader = new BufferedReader(new StringReader("some string"));

Why use a Mock object in your test classes when you could use a real one with all its state and behaviour?

当您可以使用具有所有状态和行为的真实对象时,为什么要在您的测试类中使用 Mock 对象?

To see more about how this works, you could look up the 'decorator' design pattern.

要了解有关其工作原理的更多信息,您可以查看“装饰者”设计模式。

回答by A. Masson

Assuming you are using Maven you can put a resource into "src/test/resources/" folder let's say "src/test/resources/wonderful-mock-data.xml". Then in you jUnit your can do:

假设您正在使用 Maven,您可以将资源放入“src/test/resources/”文件夹,比如“src/test/resources/ wonder-mock-data.xml”。然后在您的 jUnit 中,您可以执行以下操作:

    String resourceInputFile = "/database-insert-test.xml";
    URL url = this.getClass().getResource(resourceInputFile);
    Assert.assertNotNull("Can't find resource " + resourceInputFile, url);

    InputStream inputStream = url.openStream();

    // Now you can just use the inputStream for method calls requiring this param
    (...)

In this example the url varialble will be nullif the given resource can't be found inside current classpath. This approach allows you to put multiple scenarios inside different resourceInputFile(s)... Also remember that all kind of resources under "src/test/resources/" (not just xml files, any kind like txt, html, jpeg, etc.) are normaly available as classpath resources from all jUnit tests.

在此示例中,如果在当前类路径中找不到给定的资源,则url 变量将为null。这种方法允许您将多个场景放在不同的资源输入文件中……还要记住,“src/test/resources/”下的所有类型的资源(不仅仅是 xml 文件,任何类型的文件,如 txt、html、jpeg 等)。 ) 通常可用作所有 jUnit 测试的类路径资源。

回答by Pentayya

@Test
    public void testReadFile() {
    TestClass ClassName = Mockito.mock(TestClass.class);
     InputStream in = Mockito.mock(InputStream.class);
     InputStreamReader inr =Mockito.mock(InputStreamReader.class);
     BufferedReader bufferedReader =Mockito.mock(BufferedReader.class);
       try {
         PowerMockito.whenNew(InputStreamReader.class).withArguments(in).thenReturn(inr);
         PowerMockito.whenNew(BufferedReader.class).withArguments(inr).thenReturn(bufferedReader);
         String line1 = "example line";
         PowerMockito.when(bufferedReader.readLine()).thenReturn(line1).thenReturn(null);
         method return type = Whitebox.invokeMethod(ClassName, "MethodName", arguement);
         assertEquals("result is::","expected", actual);
     } catch (Exception e) {
         e.printStackTrace();
     }
 }

回答by Pritesh

The best solution i found is use

我发现的最佳解决方案是使用

final InputStream inputStream1 = IOUtils.toInputStream("yourdata");

and then wrap the inpustream in bufferedReader best way to write test around input Stream

然后将输入流包装在 bufferedReader 中以围绕输入流编写测试的最佳方式

回答by eyveer

String testString = "test\nstring";
InputStream stream = new ByteArrayInputStream(testString.getBytes(StandardCharsets.UTF_8));

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));

Assert.assertEquals("test", reader.readLine());
Assert.assertEquals("string", reader.readLine());

回答by byte mamba

when(imageService.saveOrUpdate(Matchers.<Image>anyObject())).thenReturn(image);

Reference http://www.javased.com/?api=org.mockito.Matchers

参考 http://www.javased.com/?api=org.mockito.Matchers