Mockito is my library of preference for all these kinds of tests (really lovely library and highly recommended). There is again an excellent post here with various comments. I just felt like providing a simplistic example + have a post to remind myself in the future.
The power of Mockito on such a scenario which actually can be something like - "I want to unit-integrate test something that inherits legacy code from super classes" is the use of Spy objects (see here as well). The power of Spy objects is that you can have a proper Mock object but you are able to invoke some real methods as well. A mixture that is.
A very simple example with a super and a sub class.
class GenericConstruct{
public String doSomethingGeneric(){
return "I do something";
}
public String doSomethingElseGeneric(){
return "I do something else generic";
}
}
class SubTypeOfGeneric extends GenericConstruct{
public String doSomethingExtra(){
System.out.println(doSomethingGeneric());
System.out.println(doSomethingEleseGeneric());
return "this is a very extra thing I am doing";
}
}
The test, creates an actual spy, mocks the 2 methods inherited from the the super() class and then goes on with the rest of the implementation.
import static org.junit.Assert.*;
import org.junit.Test;
import org.mockito.Mockito;
public class TheTest {
@Test
public void test() {
SubTypeOfGeneric aSpy = Mockito.spy(new SubTypeOfGeneric());
Mockito.doReturn("a random value").when((GenericConstruct)aSpy).doSomethingGeneric();
Mockito.doReturn("another random value").when((GenericConstruct)aSpy).doSomethingElseGeneric();
String result =aSpy.doSomethingExtra();
assertTrue(!result.isEmpty());
}
}
Happy mocking!
0 comments:
Post a Comment