In the how-to series today I will show how-to mock constructors using PowerMocks - Mocks on Steroids!. In my previous post we saw how can we write unit-tests for mocking final methods and classes.
Again, taking a fictitious example, lets say that ServiceA creates an instance of ServiceB and invokes a businessOperation on ServiceB's instance. ServiceB's constructor is evil and it throws a Exception. We want to test this code. Lets look at the code under test
As we can see, ServiceA's doSomething method create an instance of ServiceB class (by invoking a constructor with no arguments) and then invokes doBusinessOperation() method. Looks like a simple class, but wait, have a look at ServiceB's constructor, its evil, it throws an exception! Now how do we mock the constructor so that we can write a good tests case for ServiceA's doSomething method? Simple, Using PowerMocks (Mockito api) :)
How will we test it - How do they do it!:
We have to use @PrepareForTest annotation with ServiceA class as, it instanciates ServiceB and we actually want to inject a stub on ServiceB so that we can verify that doBusinessOperation method was actually invoked.
Then, we use the whenNew method of PowerMockito to actually return a stub of ServiceB when a new instance of ServiceB is created using a no argument constructor.
Just read the above line in and then compare the syntax below
We can actually read the code in English and it does make a lot of sense!
Lets look at the test code now:
Piece of cake isn't!