【问题标题】:Test code with Exceptions and with no exceptions at same time (JAVA)测试有异常的代码,同时没有异常(JAVA)
【发布时间】:2014-12-19 07:02:14
【问题描述】:

我正在为已构建的 java 类函数编写测试。我正在使用 Testng 和 Mockito 编写测试,并且有一个数据提供者。

这是我的测试

@Test(dataProvider = "myProvider", dataProviderClass = StaticDataProvider.class,
        expectedExceptions = SomeException.class)

public void myControllerTest(String argument) throws Exception {
    // Mocked object bussiness\
    Boolean resultantObject = business.getList(argument);
    Assert.assertTrue(resultantObject);
}

这是我要测试的控制器

public Boolean controller(String argument) {
    if(argument != null) {
        throw new someException();
    } else {
        System.out.println("Sucess");
        return true;
    }
}

这是我的数据提供者

@DataProvider(name = "myProvider")
public static Object[][] getDirectoryList() throws Exception {
    Object[][] result = null;
    // case1 throws SomeException
    String testData1 = null;
    // case2 don't throw exception
    String testData2 = "String";
    result = new Object[][] { { testData1 }, { testData2 } };
    return result;
}

我面临的问题是,我不想创建另一个测试来测试错误和非错误代码并使用单个测试用例完成我的测试覆盖。但是当我把 Expected Exception 放在最上面时,它会在正确的代码上失败,而当我不这样做时,它会在错误的代码上失败。

注意:这是示例代码,可能不起作用,这只是为了了解我正在处理的场景和我的期望。

【问题讨论】:

  • 不同的期望:不同的测试用例。
  • 有没有什么办法可以一次性完成呢

标签: java unit-testing testing testng mockito


【解决方案1】:

即使您忽略“一个测试,一个断言”的纯粹主义观点,我认为大多数人都同意您应该将涉及错误条件的测试与证明正常行为的测试分开。

如果您想在一个测试中测试多个错误条件(或者如果您真的热衷于继续您的计划),您可以使用此模式:

try {
  // something that should cause an exception
  fail("Exception expected");
} catch (ExactlyTheRightException e) {
  // ignored
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-29
    • 2012-04-05
    • 1970-01-01
    • 2012-03-30
    • 2020-12-21
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多