【问题标题】:EasyMock issue using addThrow to expect ExceptionEasyMock 问题使用 addThrow 期望异常
【发布时间】:2012-03-20 11:22:56
【问题描述】:

我正在尝试使用 TestNG 运行给定 here 的 EasyMock 示例,但遇到了一个奇怪的问题。前两个测试运行良好,但如果我单独运行,第三个测试 (getPriceDataAccessThrowsRuntimeException) 运行成功。但是,当我单独或一起运行其他两个测试时,第三个测试失败,我得到以下结果:

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);
}

各位大侠,我到底做错了什么?

【问题讨论】:

    标签: exception testng easymock


    【解决方案1】:

    在从 JUnit 转换到 TestNG 时,您似乎犯了一个错误。在linked example 中,doBeforeEachTestCase 方法在每个测试用例之前运行,这会将模拟依赖项重置为其基本状态。您还没有包含所有代码:您应该拥有 doBeforeEachTestCase annotatedBeforeMethod 以使用 TestNG 运行它。

    【讨论】:

    • 非常感谢,我怎么能错过!有一段时间我写了我的测试。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多