【问题标题】:Mocking Socket.getOutputStream() for testing Java模拟 Socket.getOutputStream() 用于测试 Java
【发布时间】:2019-03-22 06:46:55
【问题描述】:

我有一段代码要测试 -

 ServerHello connect(
        int version, Collection<Integer> cipherSuites)
    {
        Socket s = null;
        try {

            if(proxy!=null) {
                s = new Socket(proxy);
            }else {
                s = new Socket();
            }
            try {
                s.connect(isa);

            } catch (IOException ioe) {
                System.err.println("could not connect to "
                    + isa + ": " + ioe.toString());
                return null;
            }
            byte[] ch = makeClientHello(version, cipherSuites);
            OutputRecord orec = new OutputRecord(
                s.getOutputStream());
            orec.setType(Constants.HANDSHAKE);
            orec.setVersion(version);
            orec.write(ch);
            orec.flush();
            ServerHello x = new ServerHello(s.getInputStream());
            return x;
        } catch (IOException ioe) {
        } finally {
            try {
                s.close();
            } catch (IOException ioe) {
                // ignored
            }
        }
        return null;
    }

我想用我自己的模拟 this.socket.getInputStream()this.socket.getOutputStream() 数据。如何设置这些数据?

另外,我想确保 this.socket.connect() 在任何测试中通过,而不会在我的测试中抛出任何异常(离线测试)。

我该怎么做?我正在使用 Mockito 框架进行测试

【问题讨论】:

    标签: java unit-testing junit mockito


    【解决方案1】:

    这相当简单,您只需要模拟您的套接字并路由您的模拟方法,使其返回您自己的流并捕获写入的数据:

    @RunWith(MockitoJUnitRunner.class)
    public class MyTest
    {
       @Mock
       private Socket socket;
    
       @Mock
       private OutputStream myOutputStream;
    
       @Captor
       private ArgumentCaptor<byte[]> valueCapture;
    
       @Test
       public void test01()
       {
         Mockito.when(socket.getOutputStream()).thenReturn(myOutputStream);
    
         //EXECUTE YOUR TEST LOGIC HERE
    
         Mockito.verify(myOutputStream).write(valueCapture.capture());
         byte[] writtenData = valueCapture.getValue();        
       }
    
    }
    

    我建议做一些教程,例如:https://www.baeldung.com/mockito-annotations 或者 https://examples.javacodegeeks.com/core-java/mockito/mockito-tutorial-beginners/

    【讨论】:

    • 问题是我究竟如何用一些数据创建自己的 OutputStream 对象?以及如何防止 socket.connect 抛出错误?
    • 您还可以模拟您的流并让它返回固定的字节数组,例如 - 以与上述相同的方式。 Mocks 永远不会抛出错误,默认情况下每个方法都将返回 null。如果您不希望它们返回 null 您需要路由您的模拟方法,或者您可以简单地让它们调用“真实”方法:@Mock(answer=Answers.CALLS_REAL_METHODS) 但在这种情况下,您不再编写适当的单元测试......那已经集成测试
    • 你能举个例子,用你自己的字节数组设置数据吗?
    • 我只需要确保 socket.connect() 不会抛出异常。然后模拟调用socket.getOutputStream和socket.getInputStream时返回的数据
    • 也:阅读我的示例,它清楚地展示了如何正确测试套接字捕获传递给它的数据
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 1970-01-01
    • 2012-08-23
    相关资源
    最近更新 更多