[JAVA] Override protected method with anonymous class to stub

During unit testing, the method I wanted to test called a protected method, but the protected method was difficult to decipher (ancient heritage) and the implementation of test cases was difficult.

So I came up with the idea of overriding the protected method with an anonymous class and stubbing it.

JUnit used 4.

<dependency>
  <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

Target.java

public class Target {

  //The method you want to test
  public int wantTesting(int x) {
    return getNum(x);
  }

  //Protected method called by the method you want to test
  protected int getNum(int x) {
    return x + 100;
  }

}

TargetTest.java

import org.junit.Assert;
import org.junit.Test;

public class TargetTest {

  @Test
  public void testWantTesting() {

    Target target = new Target();
    Assert.assertEquals(101, target.wantTesting(1));

    Target target2 = new Target() {

      @Override
      protected int getNum(int x) {
        return 9999;
      }

    };

    Assert.assertEquals(9999, target2.wantTesting(1));
  }

}

Recommended Posts

Override protected method with anonymous class to stub
Introduction to algorithms with java-Shakutori method
[Java] How to compare with equals method
Anonymous class (anonymous class)
Class method
Anonymous class (aiming to introduce stream api)
Add class only to specific elements with V-for
How to avoid exceptions with Java's equals method
Method to search
Java anonymous class
[Java] How to use compareTo method of Date class
I want to call a method of another class
[Ruby] Method to easily get the receiver type .class
How to create and execute method, Proc, Method class objects