We had a really long interface, that needed to be mocked. One class's contructor had this interface object as an argument.
With my traditional mocking approach, I would have written a @Mockclass that implements this interface, @Mock only the required method, and leave other methods unimplemented. Create a new instance of this mocked class. But that looked like BIG non required code.
With my traditional mocking approach, I would have written a @Mockclass that implements this interface, @Mock only the required method, and leave other methods unimplemented. Create a new instance of this mocked class. But that looked like BIG non required code.
@Injectable to rescue
JMockit have @Injectable annotation that you pass to test method as a parameter and define the Expectation. And thats it. Here is the code snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ABC { | |
private SomeService service; | |
ABC(SomeService service) { | |
this.service = service; | |
} | |
void doSomething() { | |
XYZ xyz = service.someMethod(); | |
} | |
} | |
class TestClass { | |
@Test | |
public void testMethod(@Injectable final SomeService service) { | |
new Expectations() {{ | |
someService.someMethod(); | |
result = new XYZ(); | |
}} | |
new ABC(service).doSomething(); | |
} | |
} |
Comments
- Divyakapati