Reputation: 13395
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?
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.
Upvotes: 0
Views: 1889
Reputation: 67387
Whenever you need PowerMock, IMO this is a bad smell and a sure sign that you should refactor your code. 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.
See this answer for a more detailed explanation (search for the string "inject" on the page).
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.
Upvotes: 2