title: Patching Java classes with a mock implementation in a unit test
body: <p>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.</p>
  
  <pre><code>public class A {
    private B b;
    public A() {
      b = new B(); // 3rd party class that calls out externally (e.g. to a db)
    }
  }
  </code></pre>
  
  <p>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?</p>
  
  <p>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.</p>
  
  <p>Python has a "mock" library that allows you to "patch" functions at run time during a test.  Does Java have something similar?</p>