2012-03-20 71 views
0

我想運行TestNG給出的EasyMock示例here,並面臨一個奇怪的問題。前兩個測試運行正常,但如果我單獨運行,則第三個Test(getPriceDataAccessThrowsRuntimeException)會成功運行。然而,當我和另外兩個測試單獨或結合在一起的第三個測試運行失敗,我得到如下:EasyMock問題使用addthrow期望異常

FAILED: getPriceDataAccessThrowsRuntimeException 
org.testng.TestException: 
Expected exception java.lang.RuntimeException but got org.testng.TestException: 
Expected exception java.lang.RuntimeException but got java.lang.AssertionError: 
    Unexpected method call DataAccess.getPriceBySku("3283947"): 

以下是測試代碼:

@Test 
public void getPrice() throws Exception { 
    // Set expectations on mocks. 
    expect(mockedDependency.getPriceBySku(SKU)).andReturn(new BigDecimal(100)); 

    // Set mocks into testing mode. 
    replay(mockedDependency); 
    final BigDecimal price = systemUnderTest.getPrice(SKU); 
    assertNotNull(price); 

    // Verify behavior. 
    verify(mockedDependency); 
} 

@Test(expectedExceptions = MyCustomException.class) 
public void getPriceNonExistentSkuThrowsException() throws Exception { 

    // Set expectations on mocks. 
    expect(mockedDependency.getPriceBySku(BAD_SKU)).andReturn(null); 

    // Set mocks into testing mode. 
    replay(mockedDependency); 
    final BigDecimal price = systemUnderTest.getPrice(BAD_SKU); 
} 

@Test(expectedExceptions = RuntimeException.class) 
public void getPriceDataAccessThrowsRuntimeException() throws Exception { 

    // Set expectations on mocks. 
    expect(mockedDependency.getPriceBySku(SKU)).andThrow(new RuntimeException("Fatal data access exception.")); 

    // Set mocks into testing mode. 
    replay(mockedDependency); 
    final BigDecimal price = systemUnderTest.getPrice(SKU); 
} 

任何想法的傢伙,有什麼我做錯了嗎?

回答

0

看起來你從JUnit轉換到TestNG時犯了一個錯誤。在linked example中,doBeforeEachTestCase方法在每個測試用例之前運行,並將模擬的依賴關係重置爲其基本狀態。你沒有包含所有的代碼:你應該有doBeforeEachTestCaseannotatedBeforeMethod用TestNG運行它。

+0

非常感謝,我怎麼會錯過!有一段時間我寫了我的測試。 – dchucks 2012-03-20 12:56:03