【问题标题】:How do I verify that a specific constructor of a given class is called?如何验证是否调用了给定类的特定构造函数?
【发布时间】:2015-12-11 11:16:27
【问题描述】:

假设下面是被测试的类:

public class MyClass {
    public void doSomething() throws FileNotFoundException {
        FileInputStream fis = new FileInputStream( "someFile.txt" );
        // .. do something about fis
    }
}

当使用 jMockit 使用参数 "someFile.txt" 调用方法 doSomething() 时,如何验证构造函数 FileInputStream( String ) 是否被调用?

我不是在寻找手动或非自动的答案。我正在寻找一个答案,它使用 JUnit 或 TestNG 等工具在模拟和间谍工具(最好是 jMockit)的帮助下使用自动化单元测试。

【问题讨论】:

  • 如果构造函数没有被正确调用,你应该在调用fis中的任何方法时得到一些异常
  • “验证”是什么意思?
  • @SajanChandran,没有得到异常并不一定意味着它已经成功调用了特定的构造函数。例如,它本可以什么都不做。
  • 那么你的合约不是构造函数被调用。合约是检查文件系统的读取是否发生。该类可以合法地调用Files.newInputStream( Paths.get("somefile.txt") )并达到要求。
  • @RickvanOsta,我不确定你是否有自动化单元测试的背景。但是,如果我能简单地做到这一点,你不认为我不会在这里发帖吗?

标签: java unit-testing junit testng jmockit


【解决方案1】:

使用 JMockit Expectations API,测试可以像方法调用一样验证构造函数调用。测试只需要将类指定为@Mocked。例如:

@Test
public void exampleTestThatVerifiesConstructorCall(@Mocked FileInputStream anyFIS)
{
    new MyClass().doSomething();

    new Verifications() {{ new FileInputStream("someFile.txt"); }};
}

也就是说,我建议避免模拟像FileInputStream 这样的低级类,它们通常只是被测类的内部实现细节。更好的测试将使用实际文件并以某种方式检查它是否按预期读取。

【讨论】:

  • +1。该方法实际上返回一个 InputStream。合同说它应该首先从类路径中检查,如果没有找到,然后检查文件系统。所以它实际上就像InputStream is = classLoader.getResourceAsStream( url ); if( is == null ) { is = new FileInputStream( url ); } return is; 我还没有想到比验证对 FIS 的构造函数调用更好的测试方法。
【解决方案2】:

您可以使用 JMockit 的 $init 来验证构造函数调用:

@Test
void testDoSomethingCallsConstructorWithStringArgument throws FileNotFoundException() {
    new MockUp<FileInputStream>() {
        @Mock(invocations = 1) // Verifies one call
        void $init(String file) {
            assertEquals("someFile.txt", file);
        }
    };

    // TODO Setup an object of MyClass
    myObject.doSomething();
}

(很遗憾我目前无法测试)

【讨论】:

    猜你喜欢
    • 2015-12-02
    • 2012-07-18
    • 1970-01-01
    • 1970-01-01
    • 2012-10-18
    • 2022-11-02
    • 2015-03-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多