TDD

Mock a superclass method with Mockito

Posted on by  
Arthur Arts

Say you want to test a method from class which extends some kind of superclass. Sometimes you can be dependent on code in the superclass, which is undesirable in a test. Now actually, the first thing you should consider is to refactor your code, because it’s violating the Single Responsibility design principle: there is more than one reason why your class is subject to change. Another advice is to favor composition over inheritence. In this way you can mock the code you are collaborating with. Having said that, sometimes you run into legacy code you just have to work with and aren’t able to refactor due to circumstances. Here’s a trick I found on Stackoverflow to “mock” a superclass method to do nothing with mockito.

public class BaseController {

     public void method() {
          validate(); // I don't want to run this!
     }
}
public class JDrivenController extends BaseController {
    public void method(){
        super.method()
        load(); // I only want to test this!
    }
}

@Test
public void testSave() {
    JDrivenController spy = Mockito.spy(new JDrivenController());

    // Prevent/stub logic in super.method()
    Mockito.doNothing().when((BaseController)spy).validate();

    // When
    spy.method();

    // Then
    verify(spy).load();
}

Continue reading →

Tasty Test Tip: Test final and static methods with PowerMock and Mockito

Posted on by  
Arthur Arts

Two of the most famous mocking frameworks EasyMock and Mockito, don't offer out of the box support for mocking final and static methods. It is often said on forums that "you don't want that" or "your code is badly designed" etc. Well this might be true some of the time, but not all of the time. So let's suppose you do have a valid reason to want to mock final or static methods, PowerMock allows you to do it. Here's how (example with Mockito):

 <dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-api-mockito</artifactId>
    <version>1.4.12</version>
    <scope>test</scope>
</dependency>

Continue reading →

shadow-left