简体   繁体   English

在方法中模拟新对象的创建

[英]mock new object creation in the method

I've got this simple method 我有这个简单的方法

@Override
public List<DataRule> parseFile(String filename) {
    IFileParser wrapper = new RuleFileParserWrapper();
    return wrapper.parseRuleFile(filename);
}

But how to create a test that would mock new invokation in Spock? 但是如何创建一个可以在Spock中模拟new调用的测试?

That way it will try to use real method 这样它将尝试使用实际方法

def "should parse file"() {
    setup:
        def parser = new DefaultRuleParser()
        def wrapper = Mock(RuleFileParserWrapper) { // [new] mock result
            parseRuleFile('filename.txt') >> []
        }
    expect:
        [] == parser.parseFile('filename.txt')
}

I could use something like expected from Powermock but I wonder is there a way to do that with Spock. 我可以使用Powermock expected ,但我想知道Spock可以做到这一点吗?

Whenever you need PowerMock, IMO this is a bad smell and a sure sign that you should refactor your code. 每当需要PowerMock,IMO时,这都是难闻的气味,并且是您应该重构代码的肯定信号。 In this case, the problem is solved by refactoring for dependency injection, either via setter or constructor injection if you do not have a DI framework in your application doing it based on annotations. 在这种情况下,如果您的应用程序中没有基于注解的DI框架,则可以通过setter或构造函数注入重构依赖项注入来解决问题。

See this answer for a more detailed explanation (search for the string "inject" on the page). 请参阅此答案以获取更详细的说明(在页面上搜索字符串“ inject”)。

The test is not the problem, the application code is! 测试不是问题,应用代码是! Good tests uncover testability problems like this, so draw your conclusions and refactor. 好的测试会发现诸如此类的可测试性问题,因此请得出结论并进行重构。 Decoupling dependencies is always a good idea. 解耦依赖关系总是一个好主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM