Advertisement
Guest User

Untitled

a guest
Jan 17th, 2020
271
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.35 KB | None | 0 0
  1. package tests;
  2.  
  3. import static org.junit.Assert.assertNotNull;
  4.  
  5. import java.net.DatagramPacket;
  6. import java.net.DatagramSocket;
  7.  
  8. import org.junit.Before;
  9. import org.junit.Ignore;
  10. import org.junit.Test;
  11. import org.junit.runner.RunWith;
  12. import org.mockito.Mock;
  13. import org.mockito.Mockito;
  14. import org.powermock.api.mockito.PowerMockito;
  15. import org.powermock.core.classloader.annotations.PrepareForTest;
  16. import org.powermock.modules.junit4.PowerMockRunner;
  17.  
  18. import ClientServerChat.Client;
  19.  
  20. @RunWith(PowerMockRunner.class) // This is to be used when we use PowerMock
  21. @PrepareForTest({DatagramSocket.class, Client.class, DatagramPacket.class}) // This
  22.                                                                             // is
  23.                                                                             // to
  24.                                                                             // be
  25.                                                                             // used
  26.                                                                             // when
  27.                                                                             // we
  28.                                                                             // use
  29.                                                                             // PowerMock
  30. public class ClientTest {
  31.  
  32.     String fileName = "directors_message.txt";
  33.     Client clientObj;
  34.     private DatagramSocket clientSocketMock;
  35.  
  36.     // This can be used to Mock objects - Using Mockito
  37.     @Mock
  38.     private DatagramPacket dataPacketMock;
  39.     private byte[] requestBytesMock = "ENTS/1.0 Request\r\nfileName\r\nintegrityValue\r\n"
  40.             .getBytes();
  41.     private byte[] responseBytesMock = "ENTS/1.0 Response\r\n0\r\nlength of  data\r\nData\r\nintegrity value\r\n"
  42.             .getBytes();
  43.  
  44.     /*
  45.      * Create new Client object before every test method
  46.      */
  47.     @Before
  48.     public void setUp() throws Exception {
  49.         clientObj = new Client();
  50.     }
  51.  
  52.     @Test
  53.     public void testConstructedObject() {
  54.         // Testing if the above constructed object is not null
  55.         assertNotNull(clientObj);
  56.     }
  57.  
  58.     @Ignore
  59.     public void testMain() throws Exception {
  60.         Client.main(new String[]{"arg1", "arg2"}); // Use Client and not
  61.                                                     // clientObj as static
  62.                                                     // method belongs to class,
  63.                                                     // not object
  64.     }
  65.  
  66.     /*
  67.      * This method tests if the messageHandling() calls the handleRequest(),
  68.      * handleResponse() and isIntegrityValueOfMessageCorrect() methods.
  69.      */
  70.     @Test
  71.     public void testMessageHandlingUsingMocks() throws Exception {
  72.  
  73.         ClientServerUtility utilityMock = Mockito
  74.                 .mock(ClientServerUtility.class); // Mocking the dependent class
  75.                                                     // ClientServerUtility
  76.         clientSocketMock = Mockito.mock(DatagramSocket.class); // Mocking the
  77.                                                                 // dependent
  78.                                                                 // class
  79.                                                                 // DatagramSocket
  80.  
  81.         // Use Power mock to create new constructor initialization mocks. Here
  82.         // "clientSocketMock" mock object is returned whenever new
  83.         // "DatagramSocket" obj is created
  84.         PowerMockito.whenNew(DatagramSocket.class).withNoArguments()
  85.                 .thenReturn(clientSocketMock);
  86.  
  87.         // Use Power mock -mockStatic to initialize final/static class objects.
  88.         // To make all the methods of the class static.
  89.         PowerMockito.mockStatic(DatagramPacket.class);
  90.         dataPacketMock = PowerMockito.mock(DatagramPacket.class);
  91.         // Mock the behavior of the DatagramPacket constructor.
  92.         PowerMockito.whenNew(DatagramPacket.class)
  93.                 .withArguments(Mockito.any(byte[].class), Mockito.anyInt())
  94.                 .thenReturn(dataPacketMock);
  95.  
  96.         // Mocking the behaviors of the mock objects . Hence if the below
  97.         // methods are called on mocks, then you can send any value you want
  98.         Mockito.when(utilityMock.messageInBytes(Mockito.anyString()))
  99.                 .thenReturn(requestBytesMock); // for handleRequest()
  100.         Mockito.when(dataPacketMock.getData()).thenReturn(requestBytesMock); // in
  101.                                                                                 // receiveResponseFromServer()
  102.         Mockito.when(utilityMock.isIntegrityValueOfMessageCorrect(
  103.                 Mockito.anyString(), Mockito.anyString())).thenReturn(true);
  104.  
  105.         // Calling the test method
  106.         clientObj.messageHandling("directors_message.txt", utilityMock);
  107.  
  108.         // Since nessageHandling is a void method, we are verifying if the mock
  109.         // objects were indeed called only once.
  110.         Mockito.verify(utilityMock, Mockito.times(1))
  111.                 .messageInBytes(Mockito.anyString());
  112.         Mockito.verify(utilityMock, Mockito.times(1))
  113.                 .isIntegrityValueOfMessageCorrect(Mockito.anyString(),
  114.                         Mockito.anyString());
  115.     }// end of testMessageHandlingUsingMocks()
  116.  
  117.     /*
  118.      * handleRequestShouldReturnDatagramSocketObj() This test checks if the
  119.      * handleRequest(String file, ClientServerUtility utility) method returns a
  120.      * non-null DatagramSocket object (which contains the details of the client
  121.      * socket).
  122.      */
  123.     @Test
  124.     public void handleRequestShouldReturnDatagramSocketObj() throws Exception {
  125.         ClientServerUtility utilityMock = Mockito
  126.                 .mock(ClientServerUtility.class); // Create a mock object of
  127.                                                     // ClientServerUtility class
  128.         Mockito.when(utilityMock.messageInBytes(Mockito.anyString()))
  129.                 .thenReturn(requestBytesMock);
  130.  
  131.         DatagramSocket clientSocketMock = PowerMockito
  132.                 .mock(DatagramSocket.class);
  133.         PowerMockito.whenNew(DatagramSocket.class).withNoArguments()
  134.                 .thenReturn(clientSocketMock); // Mocking the constructor of
  135.                                                 // DatagramSocket
  136.  
  137.         assertSame(clientObj.handleRequest(fileName, utilityMock),
  138.                 clientSocketMock);
  139.     }// end of handleRequestShouldReturnDatagramSocketObj()
  140.  
  141.     /*
  142.      * generateRequestMessageShouldReturnMessage() This method tests
  143.      * generateRequestMessage() and checks if the generated request is correct
  144.      * by comparing it with the expected request message.
  145.      */
  146.     @Test
  147.     public void generateRequestMessageShouldReturnMessage() throws Exception {
  148.         ClientServerUtility utilityMock = Mockito
  149.                 .mock(ClientServerUtility.class); // Create a mock object of
  150.                                                     // ClientServerUtility class
  151.         String assembledRequest = "ENTS/1.0 Request\r\n" + fileName + "\r\n"; // Create
  152.                                                                                 // the
  153.                                                                                 // message
  154.                                                                                 // with
  155.                                                                                 // the
  156.                                                                                 // first
  157.                                                                                 // and
  158.                                                                                 // the
  159.                                                                                 // second
  160.                                                                                 // lines.
  161.         Mockito.when(utilityMock.getIntegrityCheckValue(assembledRequest))
  162.                 .thenReturn("21"); // We need to get the integrity value of the
  163.                                     // created message. This value will be the
  164.                                     // 3rd line.
  165.         String expectedRequest = "ENTS/1.0 Request\r\ndirectors_message.txt\r\n"
  166.                 + utilityMock.getIntegrityCheckValue(assembledRequest) + "\r\n"; // Create
  167.                                                                                     // the
  168.                                                                                     // expected
  169.                                                                                     // message
  170.                                                                                     // with
  171.                                                                                     // the
  172.                                                                                     // integrity
  173.                                                                                     // value
  174.         assertEquals(expectedRequest,
  175.                 Client.generateRequestMessage(fileName, utilityMock)); // assert
  176.                                                                         // if
  177.                                                                         // the
  178.                                                                         // generated
  179.                                                                         // request
  180.                                                                         // message
  181.                                                                         // is
  182.                                                                         // same
  183.                                                                         // as
  184.                                                                         // the
  185.                                                                         // expected
  186.                                                                         // message
  187.     }// end of generateRequestMessageShouldReturnMessage()
  188.  
  189.     /*
  190.      * sendRequestToServerShouldReturnDataGramSocketObj() This method tests if
  191.      * the request is sent and the returns the socket details which is required
  192.      * to receive the response.
  193.      */
  194.     @Test
  195.     public void sendRequestToServerShouldReturnDataGramSocketObj()
  196.             throws Exception {
  197.         byte[] requestToBeSent = "ENTS/1.0 Request\r\ndirectors_message.txt\r\n21\r\n"
  198.                 .getBytes();
  199.         DatagramSocket clientSocketMock = PowerMockito
  200.                 .mock(DatagramSocket.class);
  201.         PowerMockito.whenNew(DatagramSocket.class).withNoArguments()
  202.                 .thenReturn(clientSocketMock);
  203.         assertSame(clientObj.sendRequestToServer(requestToBeSent),
  204.                 clientSocketMock);
  205.     }// end of sendRequestToServerShouldReturnDataGramSocketObj()
  206.  
  207.     /*
  208.      * handleResponseShouldReturnReceivedResponse() This method checks if
  209.      * handleResponse() receives the expected response from the server.
  210.      */
  211.     @Test
  212.     public void handleResponseShouldReturnReceivedResponse() throws Exception {
  213.         ClientServerUtility utilityMock = Mockito
  214.                 .mock(ClientServerUtility.class); // Create a mock object of
  215.                                                     // ClientServerUtility class
  216.         // Use Power mock -mockStatic to initialize final/static class objects.
  217.         // To make all the methods of the class static.
  218.         PowerMockito.mockStatic(DatagramPacket.class);
  219.         PowerMockito.mockStatic(DatagramSocket.class);
  220.         dataPacketMock = PowerMockito.mock(DatagramPacket.class);
  221.         clientSocketMock = PowerMockito.mock(DatagramSocket.class);
  222.  
  223.         // Mock the behavior of the DatagramPacket constructor.
  224.         PowerMockito.whenNew(DatagramPacket.class)
  225.                 .withArguments(Mockito.any(byte[].class), Mockito.anyInt())
  226.                 .thenReturn(dataPacketMock);
  227.  
  228.         // Mocking the behaviors of the mock objects . Hence if the below
  229.         // methods are called on mocks, then you can send any value you want
  230.         Mockito.when(dataPacketMock.getData()).thenReturn(responseBytesMock); // in
  231.                                                                                 // receiveResponseFromServer()
  232.  
  233.         assertEquals(new String(responseBytesMock), clientObj
  234.                 .handleResponse(clientSocketMock, fileName, utilityMock));
  235.     } // end of handleResponseShouldReturnReceivedResponse()
  236.  
  237.     /*
  238.      * This method checks if receiveResponse() receives the expected response
  239.      * BYTES from the server.
  240.      */
  241.     @Test
  242.     public void receiveResponseFromServerShouldReturnResponseBytes()
  243.             throws Exception {
  244.         ClientServerUtility utilityMock = Mockito
  245.                 .mock(ClientServerUtility.class); // Create a mock object of
  246.                                                     // ClientServerUtility class
  247.         // Use Power mock -mockStatic to initialize final/static class objects.
  248.         // To make all the methods of the class static.
  249.         PowerMockito.mockStatic(DatagramPacket.class);
  250.         PowerMockito.mockStatic(DatagramSocket.class);
  251.         dataPacketMock = PowerMockito.mock(DatagramPacket.class);
  252.         clientSocketMock = PowerMockito.mock(DatagramSocket.class);
  253.  
  254.         // Mock the behavior of the DatagramPacket constructor.
  255.         PowerMockito.whenNew(DatagramPacket.class)
  256.                 .withArguments(Mockito.any(byte[].class), Mockito.anyInt())
  257.                 .thenReturn(dataPacketMock);
  258.  
  259.         // Mocking the behaviors of the mock objects . Hence if the below
  260.         // methods are called on mocks, then you can send any value you want
  261.         Mockito.when(dataPacketMock.getData()).thenReturn(responseBytesMock); // in
  262.                                                                                 // receiveResponseFromServer()
  263.  
  264.         assertEquals(responseBytesMock, clientObj.receiveResponseFromServer(
  265.                 clientSocketMock, fileName, utilityMock));
  266.     } // end of receiveResponseFromServerShouldReturnResponseBytes()
  267.  
  268. }// end of Test class ClientTest.java
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement