2016-09-30 128 views
0

我有以下代碼TestNG的模擬方法的返回值

private EditAttribute editAttr; 
@Mock 
private EditAttributeService editAttrServ; 

@Mock 
private EditAttributeDAO editAttributeDAO; 

@DataProvider(name = "getNamesValues") 
public Object[][] createData1() { 
return new Object[][] { 
    { new EditAttribute.Builder().bioId("abc").sheetId("12e").fid("9BD2B75E-3B00-11DF-B7E4-005056A3157F").context("[{\"id\": 'B8031714-F23B-11DF-8F44-005056A3157F_C4B10A72-F25C-11DF-8F44-005056A3157F',\"value\": \"123\"},{\"id\": '4AB3CB04-2527-11DF-994B-005056A3157F_00CA7BCA-3B9B-11DF-B7E4-005056A3157F' ,\"value\": \"12322\"}]").target("").value("").build() } 

}; 
} 

@BeforeClass 
public void setUp() { 
    MockitoAnnotations.initMocks(this); 
    editAttrServ = new EditAttributeService(); 
} 


@Test(dataProvider ="getNamesValues") 
public void TestselectAttributes(EditAttribute editAttribute){ 
    LinkedHashMap<String,LinkedList<String>> queryRes=new LinkedHashMap<String,LinkedList<String>>(); 
    LinkedList<String> columnsnames=new LinkedList<String>(); 
    columnsnames.add("city"); 
    queryRes.put("ColumnName",columnsnames); 
    LinkedList<String> tableName=new LinkedList<String>(); 
    tableName.add("Dim_Plant"); 
    queryRes.put("TableName",tableName); 
    System.out.println("queryRes="+queryRes.size()); 
    Mockito.when(editAttributeDAO.getNames("", "", "", "", "")).thenReturn(queryRes); 

    Assert.assertEquals(editAttrServ.selectAttribute(editAttribute,"","").size(),2); 
} 

方法editAttributeDAO.getNames( 「」, 「」, 「」, 「」, 「」)確實給DAO類方法的調用。我期待這種方法不被執行,因爲我使用mockito時和定義返回值。但似乎失敗,方法被調用。難道我做錯了什麼?

+1

BeforeClass通常期望setUp方法是靜態的,並且引用'this'並不是真的在那裏。嘗試之前(BeforeClass通常會引發異常,如果您嘗試註釋非靜態成員,但我正在使用Mockito 2.0.2-beta)。請參閱:http://junit.org/junit4/javadoc/latest/org/junit/package-summary.html – AlexC

+0

「EditAttributeDAO」和「EditAttributeDAO.getNames」是公共的,非靜態的還是非最終的? –

回答

0

我無法理解您的測試。前9條線似乎都是您測試設置的一部分。因此,我假定「selectAttribute」是您正在測試的業務方法。但是,您的代碼也在模擬對象上調用該方法。 EditAttributeService是一個接口還是一個類?如果它是一個接口,那麼Mockito會嘲笑你的selectAttribute方法並返回一個空集合。如果它是一個類,它將執行現有的方法,但你沒有告訴模擬的editAttributeService它是如何鏈接到「editAttributesDAO」的,這很可能是爲什麼它沒有使用你在測試開始時設置的結果方法。