我有一个名为service .class的服务类和两个名为a .class和B.class的类服务类有一个方法,该方法调用基于类a的对象的方法;B.那么我如何创建模拟对象的A &这样我就可以在服务类方法中传递那个mock对象。这是JUnit测试所需要的。如。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();
}
编辑:我的JUnit课我已经创建了两个类
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
您可以在测试中简单地模拟它们。
首先添加以下导入:import static org.mockito.Mockito.*;
然后在你的代码
//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);
然后将它们作为参数传递给Service构造函数。
如果没有存根,你模拟的类方法将返回空值,通过存根你可以指定它们应该返回什么值。
下面的代码显示测试方法返回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);