1

Is it possible to use mocks within a constructor?

Class A{

    public B b = new B();

    public A( String input ){

        //I need to stub this method
        b.someMethod( input );
    }

    // Class implementations
}

Unit Test:

Class ATest{

    @Mock
    B b;
    @InjectMock
    A a;

    //option1:
    @Before
    setup(){
        MockitoAnnotations.initMocks( this ); //Fails - since A isnt instantiated
        a = new A();
    }

    //option2:
    @Before
    setup(){
        a = new A();
        MockitoAnnotations.initMocks( this ); // Fails in new A() due to method i want to stub as mocks werent initialized yet !
    }
}

How can i approach this? thanks in advance.

3
  • 2
    You really should avoid doing logic in the constructor.
    – vertti
    May 1, 2013 at 4:53
  • Does option 1 fail if you omit a = new A();? I would have expected the @InjectMocks annotation to instantiate A for you, in the call to initMocks. For alternate options, you may get some joy from code.google.com/p/mockito/wiki/MockingObjectCreation May 1, 2013 at 5:48
  • Yes it fails complaining it has to be instantiated
    – broun
    May 2, 2013 at 4:59

2 Answers 2

7

This kind of design is hard to mock, and reveals a possible design flaw or at least weakness in your class under test. It probably calls for some kind of injection framework (i.e. Spring), so that you aren't explicitly calling the B constructor. Then your second test attempt would be spot on

If Spring is too heavy handed, there are lighter injection frameworks. Or finally, you could just pass B in as a constructor argument for A. Then you would have to use Mockito.mock(B.class) to make your B mock before passing it into the A constructor (and then you would forgo the use of the Mockito annotations).

1
  • First thank for the response. Yes, like you said spring injection would work but this class is a part of a library, and shouldnt force a Spring dependency. The second option you mentioned will work but I was hoping if there is a clean solution for the issue.
    – broun
    May 1, 2013 at 5:13
0

I don't understand precisely what you are trying to do from this, but your second approach is correct. Only you need to instantiate the B class just as you did for A class. So, basically this is all you will need to do:

//option2:
@Before
setup(){

a = new A();
b = new B();
MockitoAnnotations.initMocks( this ); // Fails in new A() due to method i want to stub as       mocks werent initialized yet !

 }
}
1
  • I could be wrong, but I think you were missing the point. Setafire wants to mock B, but you are instantiating the real one. May 1, 2013 at 4:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.