简体   繁体   中英

Mocking Socket.getOutputStream() for testing Java

I have a piece of code I'd like to test -

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

I want to mock this.socket.getInputStream() and this.socket.getOutputStream() data with my own. How do I set this data?

And also, I want o make sure that this.socket.connect() passes in any test without throwing any exceptions in my tests (offline tests).

How do I do it ? I'm using Mockito framework for tests

Its rather easy, you simply need to mock your socket and route your mock-method in such a way that it returns your own stream and capture the written data :

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

}

I recommend doing some sort of tutorial, for example : https://www.baeldung.com/mockito-annotations or maybe https://examples.javacodegeeks.com/core-java/mockito/mockito-tutorial-beginners/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM