title: Java mocks - dynamically replace class with mock object
body: <p>I'd like all instances of a class to be replaced with a mock at run time. Is this possible? For example, in a test, I would like to mark <code>class Bar</code> as a mocked class. In test scope, inside <code>class Foo</code>'s constructor, <code>new Bar()</code> should return a mocked instance of <code>Bar</code>, not the real class.</p>
  
  <pre><code>class Bar {
      public int GiveMe5() {
          return 5;
      }
  }
  
  public class Foo {
      private Bar bar;
  
      Foo() {
          bar = new Bar();
      }
  }
  </code></pre>
  
  <p>Then in my test:</p>
  
  <pre><code>class TestFoo {
      @Before
      public void setUp() {
          // Tell the mocking framework every instance of Bar should be replaced with a mocked instance
      }
      @Test
      private void testFoo() {
          Foo foo = new Foo(); // Foo.bar should reference a mocked instance of Bar()
      }
  }
  </code></pre>