Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Patching Java classes with a mock implementation in a unit test

I have a class A which instantiates an object from class B internally. That second class has lots of external side-effects, e.g. it uses a network connection.

public class A {
  private B b;
  public A() {
    b = new B(); // 3rd party class that calls out externally (e.g. to a db)
  }
}

I would like to unit test class A by providing a mock implementation of class B. I can easily create a mocked version of B by writing my own class or using something like Mockito and other frameworks, but how do I inject this mock implementation into class A's code?

I guess I could ask for an instance of class B in class A's constructor, but that seems ugly. No one really needs to know how class A does it's business.

Python has a "mock" library that allows you to "patch" functions at run time during a test. Does Java have something similar?

like image 882
oneself Avatar asked Mar 06 '26 09:03

oneself


1 Answers

In this scenario I typically have a 2nd package (default) scope constuctor that allows you to pass a mock in for testing purposes.

public class A {
  private B b;

  /*
  *  Used by clients
  */
  public A() {
    this(new B());
  }

  /*
  * Used by unit test
  * 
  * @param b A mock implementation of B
  */
  A(B b) {
    this.b = b;
  }
}
like image 99
Martin Avatar answered Mar 08 '26 21:03

Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!