简体   繁体   中英

Mock final new instance created?

How to mock private final MockClass mockClass = new MockClass();

 public class SimpleClass {
     private final MockClass mockClass = new MockClass();
 }

Use dependency injection; then you can have whatever you want in the field:

class SimpleClass {
  private final MockClass mockClass;

  SimpleClass(MockClass mockClass) {
    this.mockClass = mockClass;
  }
}

See Misko Hevery's guide to writing testable code : your code is an example of the warning sign "new keyword in a constructor or at field declaration".

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