2017-06-16 53 views
0

所以我打破我的代碼位,使之更普遍,也更容易讓別人用類似問題的Mockito當()不工作

這是我的主要代碼明白:

protected void methodA(String name) { 
     Invocation.Builder requestBuilder = webTarget.request(); 
     requestBuilder.header(HttpHeaders.AUTHORIZATION, authent.getPassword()); 

      response = request.invoke(); 

      if (response.equals("unsuccessfull")) { 
       log.warn("warning blabla: {} ({})"); 
      } else { 
       log.info("info blabla {}"); 
      } 
     } 
    } 
} 

而我的測試代碼如下所示:

@Test 
public void testMethodA() throws Exception {    
    final String name = "testName"; 

    this.subject.methodA(name); 

    Authent authent = Mockito.mock(Authent.class); 

    when(authent.getPassword()).thenReturn("testPW"); 
    assertEquals(1, logger.infos.size()); 

} 

正如我所說的代碼是更復雜的我打破了下來,並使其更短.....希望它仍然是可讀的。

我的問題不是我的when().thenReturn()不起作用,因此我的代碼不會進一步......我猜我的嘲笑由於某種原因無法正常工作。

回答

1

您測試methodA()方法,但你嘲笑Authent類和調用測試方法之後錄製的行爲吧:

this.subject.methodA(name); 
Authent authent = Mockito.mock(Authent.class); 
when(authent.getPassword()).thenReturn("testPW"); 

這是無奈的方法來測試已經調用。
應該以相反的方式來完成:

Authent authent = Mockito.mock(Authent.class); 
when(authent.getPassword()).thenReturn("testPW"); 
this.subject.methodA(name); 

此外,嘲笑一個目的是第一步。
如果模擬對象未與測試對象關聯,則它不會影響被測對象。

你應該做一些這樣的:

Authent authent = Mockito.mock(Authent.class); 
// record behavior for the mock 
when(authent.getPassword()).thenReturn("testPW"); 

// create the object under test with the mock 
this.subject = new Subject(authent); 

// call your method to test 
this.subject.methodA(name); 

// do your assertions 
... 
+0

這裏藏漢我得到一個空指針異常,因爲AUTHENT是「空」即使我實現它,你在這裏做 – Nali

+0

你確定了'主題(Authent Authent);'構造函數將'authent'參數賦值給它的'Authent authent'字段? – davidxxx

+0

是的我在我的主類和具有以下代碼'this.authent = authent;' – Nali

1

您必須調用該方法測試之前嘲笑。 你也必須將這個模擬注入你的課堂。

隨着增加結構的意見,這將是這樣的:

@Test 
public void testMethodA() throws Exception {    
    // Arrange 
    final String name = "testName"; 
    Authent authentMock = Mockito.mock(Authent.class); 
    when(authentMock.getPassword()).thenReturn("testPW"); 

    this.subject.setAuthent(authentMock); 

    // Act 
    this.subject.methodA(name); 

    // Assert 
    assertEquals(1, logger.infos.size()); 

} 
+0

現在我得到一個空指針異常,因爲雖然我在這裏實現它,但authenticntMock爲「null」 – Nali

+0

嘗試添加在您的測試類 –

+0

創建this.subject實例的代碼好吧我得到了問題我在我的主類自動裝配的其他領域似乎現在是空的,我想我必須嘲笑他們,即使我沒有想要?如果它們用於被測方法中,則爲 – Nali