How do you mock an object instantiated inside another object in Groovy?
Here's my example code
class CommandLine {
def ls() {
def cmd = "ls".execute开发者_高级运维()
if(cmd.waitFor() != 0) {
throw new Execution()
}
return cmd.text
}
}
The cmd
variable holds an object of type java.lang.Process. How would I mock out the waitFor()
method in order to test the thrown exception? If I can't, is there some way this could be rewritten to facilitate automated testing?
In general, how do you mock an object instantiated inside another class, or how do you structure your code to allow for testing?
I'm not familiar with Groovy, but if there's a chance of mocking the method String#execute()
to return a mocked Process
with a method waitFor()
which returns not zero result it would be the way to do it
Something like:
Process mockedProcess = MockingFramework.mock(Process.class); // MockingFramework can be Mockito
MockingFramework.when(String.execute()).thenReturn(mockedProcess);
MockingFramework.when(mockedProcess.waitFor).thenReturn(1);
new CommandLine().ls(); // Boom! => Execution exception
The answer is to use Groovy mocks instead of the built in Grails mocks.
import groovy.mock.interceptor.MockFor
class TestClass {
def test() {
def mock = new MockFor(classToBeMocked)
mock.demand.methodToBeMocked(1..1) { -> /* code */ }
mock.use {
/*
All calls to objects of type classToBeMocked will be
intercepted within this block of code.
*/
}
}
}
精彩评论