Showing posts with label interaction based testing. Show all posts
Showing posts with label interaction based testing. Show all posts

Sunday, August 29, 2010

How to mock/stub void static methods using PowerMock

In my previous post we saw how we could mock/stub void instance methods.
In this post we will try our hands at mocking/stubbing another exotic species called void static methods

Yes, I know void static methods should be avoided at all costs!

But sometimes you just cant help it!

So lets look at the code under test

In our example we want to test the upgradeAllCustomers method of the CustomerController.

This method upgrades all customers by invoking a void static method upgradeAll on Customer class. Currently implementation of upgradeAll method of Customer class throws and exception.  

What do we want to test:
  • upgradeAll void static method of Customer class was invoked
  • true is returned after the upgrade
How will we test it - How do they do it!:

The syntax that we had seen in the earlier post will now work anymore

If we notice persist is an instance method on the Customer class (and the above syntax works for instance methods only).

But in this case we want to stub the void static method. How do we do it?

We have to do the following things

  • Use the annotation @RunWith(PowerMockRunner.class) to bootstrap PowerMock itself
  • Use the annotation @PrepareForTest(Customer.class) to be able to stub static methods of Customer class.
  • Stub the void static method using the following lines of code

Notice that the syntax is a bit like record-playback-verify style.

We have to first tell PowerMock to do nothing when a static method is invoked on Customer class.

PowerMock should do nothing on which void static method is specified in the next line by invoking the void static upgradeAll method on the Customer class.

Its effectively recording the fact that, when static void upgradeAll method is invoked on Customer class nothing is to be done!

Before moving, lets see how can we verify that a void static method was actually invoked?

We can easily see that the syntax to verify that a static method was invoked also follows the record-playback-verify pattern.

First we have to inform PowerMock that we are going to verify a static method invocation, and in the next line we actually verify the call to the upgradeAll method.

Enough explanation lets look at the complete test code:

Yes thats how we do it!

For the first time I have to say, and believe me I hate to do so but, I don't like this syntax that much!

But that's just me and hats of to the excellent job that PowerMock and Mockito guys have done so far!

How to mock/stub void methods using PowerMock

Ok, I had though that the previous post would be the last post in the how-to series, but there are so many features in PowerMock that I am tempted to write more about it :)

So, here comes another post on how to mock/stub void methods using PowerMock.

One would think why are void methods so special, that we need a post to explain them?

Well thats because they are void methods. They don't return anything. If you remember, from my earlier post, the syntax of stubbing any method with a non void return type is as follows

In the above example doSomething method of ServiceA instance returns a String.

But imagine what will be the syntax, if doSomething method's return type was void!

May be something like this?

But, if you think for a moment about the above syntax, we would realize that  

methods in java are not very happy to accept void as the argument type!

Effectively, in the above syntax the when method is taking void as one of the argument!

Well this is a problem. This cannot happen!  Hence, we need a special syntax to mock/stub void methods.

So without wasting any more time lets look at the code under test:

In our example we want to test the persistCustomer method of the CustomerController. This method simply calls persist method on the Customer instance passed as argument. Assuming that the persist method of the Customer class returns nothing if everything is fine and throws a RuntimeException if something horribly goes wrong.

We want to write the test case for both these scenarios. So how do we do it?

How will we test it - How do they do it!:

Well, there is always a way with PowerMock!

Our first scenario is to verify that the persistCustomer method returns true if everything goes fine.

PowerMock uses the following syntax to stub the void method to do nothing.


If we read the syntax in pure English it says,

Do nothing when persist method is invoked on customer instance

As simple as that! We are telling the mock customer object to do nothing when persist method is invoked.

Lets look at the test case:


Now the other scenario, we want to make sure that false is returned when an exception is thrown from the persist method of customer instance, but for that to happen we have to stub the persist method of customer to throw an exception.

This is how we do it:

Syntax in English:

Throw RuntimeException when persist method of customer instance is invoked.

Lets look at the test case:

Thats it! Well you see there always is an easy solution with PowerMock

Tuesday, May 25, 2010

How to partially mock a class and its private methods using PowerMock

Earlier, in the how-to series we had seen how-to mock constructors.  In this post we will have a look at how-to partially mock classes and even their private methods using PowerMocks - Mocks on Steroids!

Lets first look at the code to test before I start with my rambling

Code under test:

We want to write a test case to test method1 of ServiceA class.  ServiceA's method1 invokes method2.  method2 performs some complicated business logic - in this case creates an instance of ServiceB and invoked doBusinessOperation on that instance.

There are two approaches to test ServiceA's method1.


  • Write the test case to mock out the ServiceB's constructor and assert that doBusinessOperation method was invoked on the mocked ServiceB object.
  • Stub the method2 call!  Only verify that from method1 a call was made to the method2.

We already know how to write tests for the first approach.  Today we are more interested in looking at how do we write tests for the second approach.

Why would we ever choose the second approach over the first approach?  May be because method2 was already tested in some other test case.  Hence, we just want to make sure that method1 calls method2 with the right arguments.

So how do we partially mock ServiceA?

How will we test it - How do they do it!:

PowerMockito class provides a method called spy to create partial mock of a class.  This method takes an instance of the class that you want to partially mock as argument (in this case ServiceA).  Why? Because we want to invoke actual implementation of method1 and mock only method2.

Syntax

Then, we want to stubb out the method2 and return some dummy value.  This how its done

Notice the difference in the syntax then the regular when-theReturn syntax.  As, if we use the when-thenReturn syntax actual call to method2 will be made!  Why? Because PowerMocks does not know whether you are setting up an expectation on a partial mock or actually invoking the method.  Hence, be careful with partial mocks and choose the right syntax.

How to verify that the method was actually called?

No surprises here.

The full test case would look like:

A variation of the above example, what if the method2 was private?  Can we still stub it?  Of-course the right answer is YES!

Code under test:

How will we test it - How do they do it!:

Now, the above doReturn-when-method2 syntax wont work.  As method2 is private and is not accessible outside the scope of the class.  How do we stub it then?

Only change is, we pass in the name of the private method to stub as string argument to when method.  when method also accepts the var args array of arguments to the method2.

To verify that the private method2 was invoked use

Here also, instead of verify we use verifyPrivate and call a invoke method which accepts, name of the private method and its arguments.

Full test case would look like this:

Yes!  Thats it.  We have achieved what we intended to do!  PowerMock's is really a valuable tool to have in once arsenal!

How to mock constructors using PowerMock

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.

Requirement:

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!

Tuesday, May 11, 2010

Testing the Untestable code using PowerMock (Mockito api)

Taking inspiration from this excellent post by Johan Haleby, today I am going to jump a few gears and show you the real power of PowerMocks.  I will show you how can we write good unit-tests to test the untestable code!

We will continue the How-To series using PowerMocks (Mockito api) but today lets look at something more complicated.

You must be thinking, if the code is untestable then how can we write unit-tests?  But, that my friend is the real power of PowerMocks, we can write unit-tests for testing untestable code as well!

So What are we testing today.

Code to Test:

The code example is taken from one of the code samples of JMockit unit-testing framework (which by the way is another powerful unit-testing framework).  At first glance the code might not look as complicated, but make a note of the following points and then think how will you ever write a unit-test for doBusinessOperationXyz method?

  • The ServiceA class is final
  • It invokes a static method on Database class called find which returns a list
  • It then creates a new instance of ServiceB class and invokes computeTotal method, passing it items retrieved from Database.find call
  • ServiceB class is final as well
  • Invokes another static method on Database class called save, passing it the EntityX instance

Wow! it seems like a really tough class to test.  Lets move ahead and write some good unit-tests to test the above code!

How will we test it - How do they do it!:

You will be surprised to know that, we could write multiple unit-tests for the above code depending on what exactly we want to test!  How awesome!

Test Requirement 1:

Lets say we want to test that, the ServiceB was invoked to compute total.

Test Code:

As usual we have to annotate the TestCase with @RunWith annotation (go here know more on why we have to do so).

We can verify that computeTotal method was invoked on ServiceB instance via a mocked ServiceB object. But if you think about this for a moment, how can we do that?  Because ServiceA's doBusinessOperationXyz is actually instantiating ServiceB.

How can we suppress this behavior and inject our mocked ServiceB object?  Simple! via byte-code manipulation of ServiceA class :)

No no, don't worry, we don't have to do byte-code manipulation on our own, PowerMocks does that for us.  All we need to tell PowerMocks is for which classes we want to perform byte-code manipulation using the @PrepareForTest annotation (go here to know more about @PrepareForTest annotation).

Another point is we want to mock static methods in Database class as well.  Hence we have to use @PrepareForTest annotation for Database class as well.

And finally, note that since we want to mock ServiceB class, which is a final class we have to use @PrepareForTest annotation for ServiceB class as well.

Enough fluff, show me the stuff!

The unit-test code looks like this

Thats all folks!  We have successfully tested the Untestable code for our first requirement


Thats all folks!  We have successfully tested the Untestable code for our first requirement

Test Requirement 2:

Lets say we want to test that, the Database was used to save EntityX.

Test Code:

Now that you have read the post so far, this one must look straightforward to you!

The test-case looks like

Thats it!

Test Requirement 3:

Database find was invoked to get the list of EntityY

Test Code:

The test-case looks a lot similar to the previous example

I promise its not much after this.

Test Requirement 4:

Should verify that EntityY list returned from Database.find was used to computeTotal

Test Code:

This is the final one.

Test Requirement 5:

Should verify that computed total was set on EntityX instance

Test code:

Done!  Its pretty evident from the above examples that testing the Untestable code is pretty easy using PowerMocks (Mockito api)

Feedback, questions and comments are welcome as usual!

Monday, May 10, 2010

How to mock final methods and classes using PowerMock

This is the second post in the how-to series of using PowerMockito to write beautiful unit-tests. In my previous post we saw how can we write unit-tests for mocking static methods.

Today, I will demostrate how we can mock final class and final methods using PowerMocks (Mockito api) - Mocks on steroids!

Requirement:

I am going to take a ficticious example, were AnotherService class's invokeFinal() method invokes a final method on the instance of FinalService class which is a final class.

Code under test:

The final method doSomething in the final Class FinalService does nothing, just throws an exception.  AnotherService's invokeFinalMethod invokes doSomething method.

Most common mocking framework in the java world cannot mock final classes/methods because they are typically based on creating proxies.  Creating proxies for final classes is not possible as we cannot subclass a final classes.

So how we do we it in PowerMocks (Mockito api)?

How will we test it - How do they do it!:

Aha! Its tad simple.  We don't need to do anything special here.

We have to use @PrepareForTest annotation with FinalService so that PowerMocks can actually mock FinalService (Go Here for explanation on @PrepareForTest).  Next up, we need to create the stub of FinalService using the following code

Then, we have two approaches

I will show both the approaches

State based testing:

Interaction based testing:

Thats it!

It is needless to say that things look pretty easy with PowerMocks (Mockito api).  They look easy because they are easy with PowerMocks!  Yes! you can with PowerMocks (Mockito api)!

Feedback, questions and comments are always welcome.
Have some Fun!