I am trying to run the EasyMock example given here with TestNG and am facing a strange issue. The first two tests run fine but the third Test (getPriceDataAccessThrowsRuntimeException) runs successfully if I run it alone. However, when I run it with other two test either individually or all together the third test fails and I get the following:
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"):
Following is the Test code:
@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);
}
Any idea guys, what am I doing wrong?
It looks like you’ve made a mistake when converting from JUnit to TestNG. In the linked example, the
doBeforeEachTestCasemethod is run before each test case and this resets the mocked dependency to its base state. You haven’t included all the code: you should havedoBeforeEachTestCaseannotated withBeforeMethodto run it with TestNG.