简体   繁体   中英

How to mock private method of an abstract class

public abstract class ClassA extends {

        public String getName(){
          String lastName = getLastName();
          return "Language"+lastName;
        }

        private String getLastName(){
          return "Java";
        }
}

I am writing the test for getName. I want to mock getLastName method. How can i do it?

You can try approach from that answer.

However, if logic in private method is complex and class needs separate testing for it, it's a sure sign that you need some refactoring.

According to SOLID principles your private method should be public, and also should be placed in derived class.

public abstract class ClassA {
  private final LastNameProvider provider;

  public ClassA(LastNameProvider provider) {
    this.provider = provider;
  }

  public String getName() {
    String lastName = provider.getLastName();
    return "Language"+lastName;
  }
}

public interface LastNameProvider {
  String getLastName()
}

public class JavaLastNameProvider {
  private String getLastName(){
    return "Java";
  }
}

With that approach you can easily replace provider in ClassA with another one for testing, or you can mock it with Mockito and so on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM