2014-06-27 49 views
2

我有一个名为Service.class AA服务类和命名的A.class和B.class 服务类两类具有基于类对象的& B.那么如何创建它的Mockito调用方法的方法A & B的对象,以便我可以在服务类方法中传递该mockito对象。这是JUnit测试所需的。 例如。 Service.class的JUnit使用的Mockito

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 
+0

Mockito.mock(的A.class)同样为B.它会给你的嘲笑对象。这是你想要的吗? – ppuskar

+0

@ppuskar请看看我的编辑我已经做了,但嘲笑使用此assertNotNull(mockedA)和mockedB以后,得到空 – user3060230

+0

。它会让你确认如果模拟对象为空或空指针是由于模拟类的方法 – ppuskar

回答

1

你可以简单地嘲笑他们。

以下导入先加: 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); 

然后它们作为参数传递给服务的构造。

没有存根,你的模拟类方法将返回空值,通过存根可以指定他们应该返回的值。下面

代码表明,测试方法会返回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); 
+0

请参阅我的编辑我已经做了,但得到空 – user3060230

+0

我修改了你的代码,请检查并得出结论。 –

+0

请检查编辑我已更改问题代码 – user3060230

相关问题