2014-06-27 43 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

相關問題