java - JUnit using mockito -


i have a service class named service.class , 2 classes named a.class , b.class service class has method calls methods based on object of classes & b. how can create mockito object of & b can pass mockito object in service class method.which needed junit testing. eg. service.class

    class service {             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;             }   , in response.class     public response method2(inputstream i1)){      return response.ok().build(); } 

edit: junit class have created both classes

     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 = service.test(new bytearrayinputstream("test").getbyte(), new bytearrayinputstream("test1").getbyte());         system.out.print(response);          assertequals(200,response.getstatus());   // here getting null pointer 

you can mock them in test.

first add following import : import static org.mockito.mockito.*;

then in code

 //you can mock concrete classes, not interfaces  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 pass them arguments service constructor.

without stubbing, mocked class methods return nulls, stubbing can specify value should return.

code below shows test method returns 400

  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 = service.test(new bytearrayinputstream("test".getbytes()));    system.out.println(i); 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -