user3060230
user3060230

Reputation: 181

JUnit using mockito

I have a a service class named Service.class and two classes named A.class and B.class Service class has a method which calls methods based on object of classes A & B. then how can i create mockito object of A & B so that I can pass that mockito object in the service class method.Which is needed for the JUnit testing. eg. Service.class

    class Service {
            A a;
            Response response;

            public Service(){

            }

            public Service(A a, B b){
                this.a= a;
                this.b = b;
            } 

            public Respose test(InputStream i,InputStream i1){
                InputStream inStreamA = a.method1(i,i1);
                Response response=  response.method2(inStreamA);

                return response;
            }


and in Response.class

   public Response method2(InputStream i1)){
     return Response.ok().build();
}

Edit: My JUnit Class I have created both classes

     A mockedA = mock(A.class);
        Response mockedResponse = mock(Response.class);

         when(mockedA.method1(new ByteArrayInputStream("test").getByte()).thenReturn(InputStream);
         when(mockedResponse.method2(new ByteArrayInputStream("test").getByte()).thenReturn(Res);

        Service service = new Service(mockedA , mockedResponse );
        Response i = service.test(new ByteArrayInputStream("test").getByte(), new ByteArrayInputStream("test1").getByte());

       System.out.print(response);  
       assertEquals(200,response.getStatus()); 

// but here i am getting null pointer

Upvotes: 2

Views: 869

Answers (1)

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1345

You can simply mock them in your test.

First add following import : import static org.mockito.Mockito.*;

then in your code

 //You can mock concrete classes, not only interfaces
 A mockedA = mock(A.class);
 B mockedB = mock(A.class);

 //stubbing
 when(mockedA.method1(any(InputStream.class))).thenReturn(null);
 when(mockedB.method2(any(InputStream.class))).thenReturn(null);

And then pass them as arguments to Service constructor.

Without stubbing, your mocked class methods will return nulls, by stubbing you can specify what value they should return.

Code below shows that test method returns 400

  A mockedA = mock(A.class);
  B mockedB = mock(B.class);

  when(mockedA.method1(new ByteArrayInputStream("test".getBytes()))).thenReturn(null);
  when(mockedB.method2(new ByteArrayInputStream("test".getBytes()))).thenReturn(null);

  Service service = new Service(mockedA , mockedB );
  String i = service.test(new ByteArrayInputStream("test".getBytes()));

  System.out.println(i);

Upvotes: 1

Related Questions