New Post

Rss

Tampilkan postingan dengan label Mocks. Tampilkan semua postingan
Tampilkan postingan dengan label Mocks. Tampilkan semua postingan
Jumat, 09 Agustus 2013
Injecting Test Doubles in Spring using Mockito and BeanPostProcessors

Injecting Test Doubles in Spring using Mockito and BeanPostProcessors


I'm pretty sure that if you have ever used Spring and are familliar with unit testing, you have encountered a problem related to injecting mocks / spies (Test Doubles) in the Spring's application context which you wouldn't want to modify. This article presents an approach how to solve this issue using Spring's components.

Project structure

Let's start with the project structure:


As usual to present a problem I'm trying to show a very simple project structure. The approach that I'm about to show could show more benefits if I made the problem more extensive as we had in our project:

  • we had dozens of interfaces and implementations autowired to lists
  • we wanted to perform some functional tests basing on the existing Spring application context 
  • we wanted to verify that for certain input conditions some specific implementation would have their methods executed 
  • we wanted to stub database access.

In this example we have a PlayerService that gets a Player using a PlayerWebService. We have an applicationContext that simply defines packages for autowiring:

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

<context:component-scan base-package="com.blogspot.toomuchcoding"/>

</beans>

Then we have our very simple model:

Player.java

package com.blogspot.toomuchcoding.model;

import java.math.BigDecimal;

/**
* User: mgrzejszczak
* Date: 08.08.13
* Time: 14:38
*/
public final class Player {
private final String playerName;
private final BigDecimal playerValue;

public Player(final String playerName, final BigDecimal playerValue) {
this.playerName = playerName;
this.playerValue = playerValue;
}

public String getPlayerName() {
return playerName;
}

public BigDecimal getPlayerValue() {
return playerValue;
}
}


the implementation of the PlayerService that uses PlayerWebService to retrieve data regarding the Player:

PlayerServiceImpl.java

package com.blogspot.toomuchcoding.service;

import com.blogspot.toomuchcoding.model.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* User: mgrzejszczak
* Date: 08.06.13
* Time: 19:02
*/
@Service
public class PlayerServiceImpl implements PlayerService {
private static final Logger LOGGER = LoggerFactory.getLogger(PlayerServiceImpl.class);

@Autowired
private PlayerWebService playerWebService;

@Override
public Player getPlayerByName(String playerName) {
LOGGER.debug(String.format("Logging the player web service name [%s]", playerWebService.getWebServiceName()));
return playerWebService.getPlayerByName(playerName);
}

public PlayerWebService getPlayerWebService() {
return playerWebService;
}

public void setPlayerWebService(PlayerWebService playerWebService) {
this.playerWebService = playerWebService;
}
}


the implementation of the PlayerWebService that is a provider of data (in this scenario we are simulating awaiting for response):

PlayerWebServiceImpl.java

package com.blogspot.toomuchcoding.service;

import com.blogspot.toomuchcoding.model.Player;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
* User: mgrzejszczak
* Date: 08.08.13
* Time: 14:48
*/
@Service
public class PlayerWebServiceImpl implements PlayerWebService {
private static final Logger LOGGER = LoggerFactory.getLogger(PlayerWebServiceImpl.class);
public static final String WEB_SERVICE_NAME = "SuperPlayerWebService";
public static final String SAMPLE_PLAYER_VALUE = "1000";

@Override
public String getWebServiceName() {
return WEB_SERVICE_NAME;
}

@Override
public Player getPlayerByName(String name) {
try {
LOGGER.debug("Simulating awaiting time for a response from a web service");
Thread.sleep(5000);
} catch (InterruptedException e) {
LOGGER.error(String.format("[%s] occurred while trying to make the thread sleep", e));
}
return new Player(name, new BigDecimal(SAMPLE_PLAYER_VALUE));
}
}

Perhaps the project structure and the methods are not one of the most brilliant you have ever seen but I wanted to keep it simple to present the problem ;)

The problem

So what actually is the problem? Let us assume that we want our autowired PlayerWebServiceImpl to be a Spy that we can verify. What is more you don't want to actually change anything in the applicationContext.xml - you want to use the current version of the Spring context.

With mocks it's easier since you can define in your XML file (using Mockito factory method) your bean as a mock to override the original implementation just like this:

    <bean id="playerWebServiceImpl" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.blogspot.toomuchcoding.service.PlayerWebServiceImpl"/>
</bean>

What about the Spy? It's more problematic since in order to create a Spy you need an already existing object of the given type. In our example we have some autowiring going on so we would have to first create a spring bean of the PlayerWebService type (Spring would have to wire all its dependencies) and then wrap it around with Mockito.spy(...) and only then would it have to be wired somewhere else... It's getting very complicatied doesn't it?

The solution

You can see that the problem is not that trivial to be solved. An easy way to fix it however is to use native Spring mechanisms - BeanPostProcessors. You can check my article about how to create a Spring BeanPostProcessor for a specified type - we'll be using it in this example.

Let's start with checking the test class:

PlayerServiceImplTest.java

package com.blogspot.toomuchcoding.service;

import com.blogspot.toomuchcoding.model.Player;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.math.BigDecimal;

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.BDDMockito.doReturn;
import static org.mockito.Mockito.verify;

/**
* User: mgrzejszczak
* Date: 08.06.13
* Time: 19:26
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:testApplicationContext.xml")
public class PlayerServiceImplTest {

public static final String PLAYER_NAME = "Lewandowski";
public static final BigDecimal PLAYER_VALUE = new BigDecimal("35000000");

@Autowired
PlayerWebService playerWebServiceSpy;

@Autowired
PlayerService objectUnderTest;

@Test
public void shouldReturnAPlayerFromPlayerWebService(){
//given
Player referencePlayer = new Player(PLAYER_NAME, PLAYER_VALUE);
doReturn(referencePlayer).when(playerWebServiceSpy).getPlayerByName(PLAYER_NAME);

//when
Player player = objectUnderTest.getPlayerByName(PLAYER_NAME);

//then
assertThat(player, is(referencePlayer));
verify(playerWebServiceSpy).getWebServiceName();
assertThat(playerWebServiceSpy.getWebServiceName(), is(PlayerWebServiceImpl.WEB_SERVICE_NAME));
}


}

In this test we want to mock retrieval of Player from the PlayerWebService (let's assume that normally it would try to send a request to the outside world - and we wouldn't want that to happen in our scenario) and test that our PlayerService returns the Player that we provided in the method stub and what is more we want to perform verification on the Spy that the method getWebServiceName() has been executed and that it has a very precisely defined return value. In other words we wanted to stub the method getPlayerByName(...) and wanted to perform verification of the spy by checking the getWebServiceName()method.

Let's check the test context:

testApplicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

<import resource="applicationContext.xml"/>
<bean class="com.blogspot.postprocessor.PlayerWebServicePostProcessor" />
</beans>

The test context is very small since it's importing the current applicationContext.xml and creating a Bean that is the key feature in this example - the BeanPostProcessor:

PlayerWebServicePostProcessor.java

package com.blogspot.postprocessor;


import com.blogspot.toomuchcoding.processor.AbstractBeanPostProcessor;
import com.blogspot.toomuchcoding.service.PlayerWebService;

import static org.mockito.Mockito.spy;

/**
* User: mgrzejszczak
* Date: 07.05.13
* Time: 11:30
*/
public class PlayerWebServicePostProcessor extends AbstractBeanPostProcessor<PlayerWebService> {
public PlayerWebServicePostProcessor() {
super(PlayerWebService.class);
}

@Override
public PlayerWebService doBefore(PlayerWebService bean) {
return spy(bean);
}

@Override
public PlayerWebService doAfter(PlayerWebService bean) {
return bean;
}
}

The class is extending the AbstractBeanPostProcessor that implements the BeanPostProcessor interface. The logic behind this class is to register the Class for which one wants to perform some actions either before initialization (postProcessBeforeInitialization) or after initialization of the bean (postProcessAfterInitialization). The AbstractBeanPostProcessor is well explained in my post Spring BeanPostProcessor for a specified type but there is one slight change - in my old post we were allowed by the abstraction to perform some actions on the bean without the possibility of returning a wrapper or a proxy on the bean.

As you can see in the case of PlayerWebServicePostProcessor before initialization we are creating a Spy using Mockito.spy(...) method. In this way we create a factory hook on the intialization of beans of given type - it's as simple as that. This method will be executed for all the classes that implement the PlayerWebService interface.

Other possibilities

While checking out current solutions to this problem I have encountered the Springockito library by Jakub Janczak.

I haven't been using this so I don't know what are (if there are any ;) ) production issues related to this library but it seems really nice and intuitive - great job Jakub! Still, you become dependent on the external library whereas in this example I've shown how to deal with the issue using Spring.

Summary

In this post I've shown how to
  • create mocks for existing beans using XML Spring configuration
  • create a BeanPostProcessor implementation that performs logic for a given class of beans
  • return Spy (you could also return a Mock) for the given class of bean
Now let's move through the Prons and Cons of my approach:

Advantages
  • you use Spring native mechanism to create Test Doubles for your beans
  • you are not required to add any additional external dependencies
  • if you use the AbstractBeanPostProcessor you have very little changes to implement
Disadvantages
  • you have to be familliar with internal Spring architecture (that it uses BeanPostProcessors) - but is it a disadvantage? ;) - in fact if you use the AbstractBeanPostProcessor  you don't have to be familliar with it - you just have to provide the class type and actions to happen before and after initialization.
  • it's less intuitive than annotations like in the Springockito library

Sources

The sources are available at TooMuchCoding BitBucket repository and TooMuchCoding Github repository.

Selasa, 06 Agustus 2013
Spock - return nested spies / mocks

Spock - return nested spies / mocks


Hi! Some time ago I have written an article about Mockito and using RETURNS_DEEP_STUBS when working with JAXB. Quite recently we have faced a similliar issue with deeply nesetd JAXB and the awesome testing framework written in Groovy called Spock. Natively Spock does not support creating deep stubs or spies so we needed to create a workaround for it and this article will show you how to do it.

Project structure

We will be working on the same data structure as in the RETURNS_DEEP_STUBS when working with JAXB article so the project structure will be quite simillar:


As you can see the main difference is such that the tests are present in the /test/groovy/ folder instead of /test/java/ folder.

Extended Spock Specification

In order to use Spock as a testing framework you have to create Groovy test scripts that extend the Spock Specification class. The details of how to use Spock are available here. In this project I have created an abstract class that extends Specification and adds two additional methods for creating nested Test Doubles (I don't remember if I haven't seen a prototype of this approach somewhere on the internet).

ExtendedSpockSpecification.groovy

package com.blogspot.toomuchcoding.spock;

import spock.lang.Specification

/**
* Created with IntelliJ IDEA.
* User: MGrzejszczak
* Date: 14.06.13
* Time: 15:26
*/
abstract class ExtendedSpockSpecification extends Specification {
/**
* The method creates nested structure of spies for all the elements present in the property parameter. Those spies are set on the input object.
*
* @param object - object on which you want to create nested spies
* @param property - field accessors delimited by a dot - JavaBean convention
* @return Spy of the last object from the property path
*/
protected def createNestedSpies(object, String property) {
def lastObject = object
property.tokenize('.').inject object, { obj, prop ->
if (obj[prop] == null) {
def foundProp = obj.metaClass.properties.find { it.name == prop }
obj[prop] = Spy(foundProp.type)
}
lastObject = obj[prop]
}
lastObject
}

/**
* The method creates nested structure of mocks for all the elements present in the property parameter. Those mocks are set on the input object.
*
* @param object - object on which you want to create nested mocks
* @param property - field accessors delimited by a dot - JavaBean convention
* @return Mock of the last object from the property path
*/
protected def createNestedMocks(object, String property) {
def lastObject = object
property.tokenize('.').inject object, { obj, prop ->
def foundProp = obj.metaClass.properties.find { it.name == prop }
def mockedProp = Mock(foundProp.type)
lastObject."${prop}" >> mockedProp
lastObject = mockedProp
}
lastObject
}
}

These two methods work in a very simillar manner.
  • Assuming that the method's argument property  looks as follows: "a.b.c.d" then the methods tokenize the string by "." and iterate over the array - ["a","b","c","d"]. 
  • We then iterate over the properties of the Meta Class to find the one whose name is equal to prop (for example "a"). 
  • If that is the case we then use Spock's Mock/Spy method to create a Test Double of a given class (type). 
  • Finally we have to bind the mocked nested element to its parent. 
    • For the Spy it's easy since we set the value on the parent (lastObject = obj[prop]). 
    • For the mocks however we need to use the overloaded >> operator to record the behavior for our mock - that's why dynamically call the property that is present in the prop variable (lastObject."${prop}" >> mockedProp). 
  • Then we return from the closure the mocked/spied instance and we repeat the process for it

Class to be tested

Let's take a look at the class to be tested:

PlayerServiceImpl.java

package com.blogspot.toomuchcoding.service;

import com.blogspot.toomuchcoding.model.PlayerDetails;

/**
* User: mgrzejszczak
* Date: 08.06.13
* Time: 19:02
*/
public class PlayerServiceImpl implements PlayerService {
@Override
public boolean isPlayerOfGivenCountry(PlayerDetails playerDetails, String country) {
String countryValue = playerDetails.getClubDetails().getCountry().getCountryCode().getCountryCode().value();
return countryValue.equalsIgnoreCase(country);
}
}

The test class

And now the test class:

PlayerServiceImplWrittenUsingSpockTest.groovy

package com.blogspot.toomuchcoding.service

import com.blogspot.toomuchcoding.model.*
import com.blogspot.toomuchcoding.spock.ExtendedSpockSpecification

/**
* User: mgrzejszczak
* Date: 14.06.13
* Time: 16:06
*/
class PlayerServiceImplWrittenUsingSpockTest extends ExtendedSpockSpecification {

public static final String COUNTRY_CODE_ENG = "ENG";

PlayerServiceImpl objectUnderTest

def setup(){
objectUnderTest = new PlayerServiceImpl()
}

def "should return true if country code is the same when creating nested structures using groovy"() {
given:
PlayerDetails playerDetails = new PlayerDetails(
clubDetails: new ClubDetails(
country: new CountryDetails(
countryCode: new CountryCodeDetails(
countryCode: CountryCodeType.ENG
)
)
)
)

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

def "should return true if country code is the same when creating nested structures using spock mocks - requires CGLIB for non interface types"() {
given:
PlayerDetails playerDetails = Mock()
ClubDetails clubDetails = Mock()
CountryDetails countryDetails = Mock()
CountryCodeDetails countryCodeDetails = Mock()
countryCodeDetails.countryCode >> CountryCodeType.ENG
countryDetails.countryCode >> countryCodeDetails
clubDetails.country >> countryDetails
playerDetails.clubDetails >> clubDetails

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}


def "should return true if country code is the same using ExtendedSpockSpecification's createNestedMocks"() {
given:
PlayerDetails playerDetails = Mock()
CountryCodeDetails countryCodeDetails = createNestedMocks(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode >> CountryCodeType.ENG

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

def "should return false if country code is not the same using ExtendedSpockSpecification createNestedMocks"() {
given:
PlayerDetails playerDetails = Mock()
CountryCodeDetails countryCodeDetails = createNestedMocks(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode >> CountryCodeType.PL

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
!playerIsOfGivenCountry
}

def "should return true if country code is the same using ExtendedSpockSpecification's createNestedSpies"() {
given:
PlayerDetails playerDetails = Spy()
CountryCodeDetails countryCodeDetails = createNestedSpies(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode = CountryCodeType.ENG

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

def "should return false if country code is not the same using ExtendedSpockSpecification's createNestedSpies"() {
given:
PlayerDetails playerDetails = Spy()
CountryCodeDetails countryCodeDetails = createNestedSpies(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode = CountryCodeType.PL

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
!playerIsOfGivenCountry
}


}

Let's move through the test methods one by one. First I present the code and then have a quick description of the presented snippet.

    def "should return true if country code is the same when creating nested structures using groovy"() {
given:
PlayerDetails playerDetails = new PlayerDetails(
clubDetails: new ClubDetails(
country: new CountryDetails(
countryCode: new CountryCodeDetails(
countryCode: CountryCodeType.ENG
)
)
)
)

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

Here you could find the approach of creating nested structures by using the Groovy feature of passing properties to be set in the constructor.

    def "should return true if country code is the same when creating nested structures using spock mocks - requires CGLIB for non interface types"() {
given:
PlayerDetails playerDetails = Mock()
ClubDetails clubDetails = Mock()
CountryDetails countryDetails = Mock()
CountryCodeDetails countryCodeDetails = Mock()
countryCodeDetails.countryCode >> CountryCodeType.ENG
countryDetails.countryCode >> countryCodeDetails
clubDetails.country >> countryDetails
playerDetails.clubDetails >> clubDetails

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

Here you can find a test that creates mocks using Spock - mind you that you need CGLIB as a dependency when you are mocking non interface types.

    def "should return true if country code is the same using ExtendedSpockSpecification's createNestedMocks"() {
given:
PlayerDetails playerDetails = Mock()
CountryCodeDetails countryCodeDetails = createNestedMocks(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode >> CountryCodeType.ENG

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

Here you have an example of creating nested mocks using the createNestedMocks method.

    def "should return false if country code is not the same using ExtendedSpockSpecification createNestedMocks"() {
given:
PlayerDetails playerDetails = Mock()
CountryCodeDetails countryCodeDetails = createNestedMocks(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode >> CountryCodeType.PL

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
!playerIsOfGivenCountry
}

An example showing that creating nested mocks using the createNestedMocks method really works - should return false for improper country code.

    def "should return true if country code is the same using ExtendedSpockSpecification's createNestedSpies"() {
given:
PlayerDetails playerDetails = Spy()
CountryCodeDetails countryCodeDetails = createNestedSpies(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode = CountryCodeType.ENG

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
playerIsOfGivenCountry
}

Here you have an example of creating nested spies using the createNestedSpies method.

    def "should return false if country code is not the same using ExtendedSpockSpecification's createNestedSpies"() {
given:
PlayerDetails playerDetails = Spy()
CountryCodeDetails countryCodeDetails = createNestedSpies(playerDetails, "clubDetails.country.countryCode")
countryCodeDetails.countryCode = CountryCodeType.PL

when:
boolean playerIsOfGivenCountry = objectUnderTest.isPlayerOfGivenCountry(playerDetails, COUNTRY_CODE_ENG);

then:
!playerIsOfGivenCountry
}

An example showing that creating nested spies using the createNestedSpies method really works - should return false for improper country code.

Summary

In this post I have shown you how you can create nested mocks and spies using Spock. It can be useful especially when you are working with nested structures such as JAXB. Still you have to bear in mind that those structures to some extend violate the Law of Demeter. If you check my previous article about Mockito you would see that:
We are getting the nested elements from the JAXB generated classes. Although it violates the Law of Demeter it is quite common to call methods of structures because JAXB generated classes are in fact structures so in fact I fully agree with Martin Fowler that it should be called the Suggestion of Demeter.
And in case of this example the idea is the same - we are talking about structures so we don't violate the Law of Demeter.

Advantages

  • With a single method you can mock/spy nested elements
  • Code cleaner than creating tons of objects that you then have to manually set

Disadvantages

  • Your IDE won't help you with providing the property names since the properties are presented as Strings
  • You have to set Test Doubles only in the Specification context (and sometimes you want to go outside this scope)

Sources

As usual the sources are available at BitBucket and GitHub.
Rabu, 24 Oktober 2012
no image

Mockito InvocationOnMock - checking an argument



Hi!

In one of my projects we had a very interesting situation in terms of testing. We couldn't mock an invocation of a static method due to the fact that PowerMock was not allowed to be used so there were plenty of objects and dependencies being initialized. What is more we were using a custom made dependency injection system that had a possibility of injecting a mock.

The problem was such that during a test we wanted to assert whether one of the objects was in a very precise state. This object was created using the new operator so we couldn't mock it (again no PowerMock allowed). Fortunately this object got passed to a method of an object that we could mock...

As presented below timeConsumingExternalService is an object that we could mock via the custom dependency injection system whereas the SomePojo class is an object whose state we would like to verify.

timeConsumingExternalService.processSomeObject(new SomePojo("name", "surname", 1, 1.0));

So what we did was that in our mock to which the object got passed we created a new Answer (the same Answer that I spoke of here). Due to which we could access the InvocationOnMock and the arguments passed to the method as such.

Mockito.doAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
Object[] object = invocation.getArguments();

if (object.length > 0) {
SomePojo somePojo = (SomePojo) object[0];

Assert.assertEquals("name", somePojo.getName());
LOGGER.debug("Names are equal");
Assert.assertEquals("surname", somePojo.getSurname());
LOGGER.debug("Surnames are equal");
Assert.assertTrue(1 == somePojo.getIntValue());
LOGGER.debug("Ints are equal");
Assert.assertTrue(1.0 == somePojo.getDoubleValue());
LOGGER.debug("Doubles are equal");

LOGGER.debug("Object being an argument of the function [" + String.valueOf(somePojo) + "]");
}
return null;
}
}).when(timeConsumingExternalServiceMock).processSomeObject(Mockito.any(SomePojo.class));

Of course the logs regarding the equalities are unnecessary since if they wouldn't be equal we would have an assertion exception - I left them for the purpose of this post.

And in the logs we can find:

pl.grzejszczak.marcin.ServiceIntegrationTest:48 Names are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:50 Surnames are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:52 Ints are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:54 Doubles are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:56 Object being an argument of the function [SomePojo [name=name, surname=surname, intValue=1, doubleValue=1.0]]

So in this way something that seems impossible to be verified can get verified :)

Update!

Thanks to Holger's suggestion I took a look at the ArgumentCaptor object and that is true that it is an elegant solution to retrieve information about the arguments executed on a method. Where InvocationOnMock can give you much more information and possibilities (for instance regarding the method being executed or just execute the real method) for this particular case a much more elegant, easier and faster way of dealing with the issue would be:


  //service that executes the external service
executorService.execute(someTask);

final ArgumentCaptor<SomePojo> argumentCaptor = ArgumentCaptor.forClass(SomePojo.class);
Mockito.verify(timeConsumingExternalServiceMock).processSomeObject(argumentCaptor.capture());
SomePojo somePojo = argumentCaptor.getValue();
Assert.assertEquals("name", somePojo.getName());
LOGGER.debug("Names are equal");
Assert.assertEquals("surname", somePojo.getSurname());
LOGGER.debug("Surnames are equal");
Assert.assertTrue(1 == somePojo.getIntValue());
LOGGER.debug("Ints are equal");
Assert.assertTrue(1.0 == somePojo.getDoubleValue());
LOGGER.debug("Doubles are equal");

The logs:
pl.grzejszczak.marcin.junit.SomeTask:26 Before processing an object
pl.grzejszczak.marcin.junit.SomeTask:28 After processing an object
pl.grzejszczak.marcin.ServiceIntegrationTest:75 Names are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:77 Surnames are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:79 Ints are equal
pl.grzejszczak.marcin.ServiceIntegrationTest:81 Doubles are equal

Thanks again Holger!
Copyright © 2012 Codding News All Right Reserved