Tag Archives: Mockito

mock Spring bean, encapsulate spring bean

How to mock Spring bean (version 2)

EDIT: As of Spring Boot 1.4.0, faking of Spring Beans is supported natively via annotation @MockBean. Read Spring Boot docs for more info.

About a year ago, I wrote a blog post how to mock Spring Bean. Patterns described there were little bit invasive to the production code.  As one of the readers Colin correctly pointed out in comment, there is better alternative to spy/mock Spring bean based on @Profile annotation. This blog post is going to describe this technique. I used this approach with success at work and also in my side projects.

Note that widespread mocking in your application is often considered as design smell.

Introducing production code

First of all we need code under test to demonstrate mocking. We will use these simple classes:

@Repository
public class AddressDao {
	public String readAddress(String userName) {
		return "3 Dark Corner";
	}
}

@Service
public class AddressService {
	private AddressDao addressDao;
	
	@Autowired
	public AddressService(AddressDao addressDao) {
		this.addressDao = addressDao;
	}
	
	public String getAddressForUser(String userName){
		return addressDao.readAddress(userName);
	}
}

@Service
public class UserService {
	private AddressService addressService;

	@Autowired
	public UserService(AddressService addressService) {
		this.addressService = addressService;
	}
	
	public String getUserDetails(String userName){
		String address = addressService.getAddressForUser(userName);
		return String.format("User %s, %s", userName, address);
	}
}

Of course this code doesn’t make much sense, but will be good to demonstrate how to mock Spring bean. AddressDao just returns string and thus simulates read from some data source. It is autowired into AddressService. This bean is autowired into UserService, which is used to construct string with user name and address.

Notice that we are using constructor injection as field injection is considered as bad practice. If you want to enforce constructor injection for your application, Oliver Gierke (Spring ecosystem developer and Spring Data lead) recently created very nice project Ninjector.

Configuration which scans all these beans is pretty standard Spring Boot main class:

@SpringBootApplication
public class SimpleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SimpleApplication.class, args);
    }
}

Mock Spring bean (without AOP)

Let’s test the AddressService class where we mock AddressDao. We can create this mock via Spring’ @Profiles and @Primary annotations this way:

@Profile("AddressService-test")
@Configuration
public class AddressDaoTestConfiguration {
	@Bean
	@Primary
	public AddressDao addressDao() {
		return Mockito.mock(AddressDao.class);
	}
}

This test configuration will be applied only when Spring profile AddressService-test is active. When it’s applied, it registers bean of type AddressDao, which is mock instance created by Mockito. @Primary annotation tells Spring to use this instance instead of real one when somebody autowire AddressDao bean.

Test class is using JUnit framework:

@ActiveProfiles("AddressService-test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SimpleApplication.class)
public class AddressServiceITest {
	@Autowired 
	private AddressService addressService;

	@Autowired
	private AddressDao addressDao;

	@Test
	public void testGetAddressForUser() {
		// GIVEN
		Mockito.when(addressDao.readAddress("john"))
			.thenReturn("5 Bright Corner");

		// WHEN 
		String actualAddress = addressService.getAddressForUser("john");
  
		// THEN   
		Assert.assertEquals("5 Bright Corner", actualAddress);
	}
}

We activate profile AddressService-test to enable AddressDao mocking. Annotation @RunWith is needed for Spring integration tests and @SpringApplicationConfiguration defines which Spring configuration will be used to construct context for testing. Before the test, we autowire instance of AddressService under test and AddressDao mock.

Subsequent testing method should be clear if you are using Mockito. In GIVEN phase, we record desired behavior into mock instance. In WHEN phase, we execute testing code and in THEN phase, we verify if testing code returned value we expect.

Spy on Spring Bean (without AOP)

For spying example, will be spying on AddressService instance:

@Profile("UserService-test")
@Configuration
public class AddressServiceTestConfiguration {
	@Bean
	@Primary
	public AddressService addressServiceSpy(AddressService addressService) {
		return Mockito.spy(addressService);
	}
}

This Spring configuration will be component scanned only if profile UserService-test will be active. It defines primary bean of type AddressService. @Primary tells Spring to use this instance in case two beans of this type are present in Spring context.  During construction of this bean we autowire existing instance of AddressService from Spring context and use Mockito’s spying feature. The bean we are registering is effectively delegating all the calls to original instance, but Mockito spying allows us to verify interactions on spied instance.

We will test behavior of UserService this way:

@ActiveProfiles("UserService-test")
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(SimpleApplication.class)
public class UserServiceITest {
	@Autowired
	private UserService userService;

	@Autowired
	private AddressService addressService;
 
	@Test
	public void testGetUserDetails() {
		// GIVEN - Spring scanned by SimpleApplication class

		// WHEN
		String actualUserDetails = userService.getUserDetails("john");
 
		// THEN
		Assert.assertEquals("User john, 3 Dark Corner", actualUserDetails);
		Mockito.verify(addressService).getAddressForUser("john");
	}
}

For testing we activate UserService-test profile so our spying configuration will be applied. We autowire UserService which is under test and AddressService, which is being spied via Mockito.

We don’t need to prepare any behavior for testing in GIVEN phase. WHEN phase is obviously executing code under test. In THEN phase we verify if testing code returned value we expect and also if addressService call was executed with correct parameter.

Problems with Mockito and Spring AOP

Let say now we want to use Spring AOP module to handle some cross-cutting concerns. For example to log calls on our Spring beans this way:

package net.lkrnac.blog.testing.mockbeanv2.aoptesting;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;
    
@Aspect
@Component
@Slf4j
@Profile("aop") //only for example purposes
public class AddressLogger {
    @Before("execution(* net.lkrnac.blog.testing.mockbeanv2.beans.*.*(..))")
    public void logAddressCall(JoinPoint jp){
        log.info("Executing method {}", jp.getSignature());
    }
}

This AOP Aspect is applied before call on Spring beans from package net.lkrnac.blog.testing.mockbeanv2. It is using Lombok’s annotation @Slf4j to log signature of called method. Notice that this bean is created only when aop profile is defined. We are using this profile to separate AOP and non-AOP testing examples. In a real application you wouldn’t want to use such profile.

We also need to enable AspectJ for our application, therefore all the following examples will be using this Spring Boot main class:

@SpringBootApplication
@EnableAspectJAutoProxy
public class AopApplication {
    public static void main(String[] args) {
        SpringApplication.run(AopApplication.class, args);
    }
}

AOP constructs are enabled by @EnableAspectJAutoProxy.

But such AOP constructs may be problematic if we combine Mockito for mocking with Spring AOP. It is because both use CGLIB to proxy real instances and when Mockito proxy is wrapped into Spring proxy, we can experience type mismatch problems. These can be mitigated by configuring bean’s scope with ScopedProxyMode.TARGET_CLASS, but Mockito verify() calls still fail with NotAMockException. Such problems can be seen if we enable aop profile for UserServiceITest.

Mock Spring bean proxied by Spring AOP

To overcome these problems, we will wrap mock into this Spring bean:

package net.lkrnac.blog.testing.mockbeanv2.aoptesting;

import org.mockito.Mockito;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Repository;

import lombok.Getter;
import net.lkrnac.blog.testing.mockbeanv2.beans.AddressDao;

@Primary
@Repository
@Profile("AddressService-aop-mock-test")
public class AddressDaoMock extends AddressDao{
    @Getter
    private AddressDao mockDelegate = Mockito.mock(AddressDao.class);
    
    public String readAddress(String userName) {
        return mockDelegate.readAddress(userName);
    }
}

@Primary annotation makes sure that this bean will take precedence before real AddressDao bean during injection. To make sure it will be applied only for specific test, we define profile AddressService-aop-mock-test for this bean. It inherits AddressDao class, so that it can act as full replacement of that type.

In order to fake behavior, we define mock instance of type AddressDao, which is exposed via getter defined by Lombok’s @Getter annotation. We also implement readAddress() method which is expected to be called during test. This method just delegates the call to mock instance.

The test where this mock is used can look like this:

@ActiveProfiles({"AddressService-aop-mock-test", "aop"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(AopApplication.class)
public class AddressServiceAopMockITest {
    @Autowired
    private AddressService addressService; 

    @Autowired
    private AddressDao addressDao;
    
    @Test
    public void testGetAddressForUser() {
        // GIVEN
        AddressDaoMock addressDaoMock = (AddressDaoMock) addressDao;
        Mockito.when(addressDaoMock.getMockDelegate().readAddress("john"))
            .thenReturn("5 Bright Corner");
 
        // WHEN 
        String actualAddress = addressService.getAddressForUser("john");
 
        // THEN  
        Assert.assertEquals("5 Bright Corner", actualAddress);
    }
}

In the test we define AddressService-aop-mock-test profile to activate AddressDaoMock and aop profile to activate AddressLogger AOP aspect. For testing, we autowire testing bean addressService and its faked dependency addressDao. As we know, addressDao will be of type AddressDaoMock, because this bean was marked as @Primary. Therefore we can cast it and record behavior into mockDelegate.

When we call testing method, recorded behavior should be used because we expect testing method to use AddressDao dependency.

Spy on Spring bean proxied by Spring AOP

Similar pattern can be used for spying the real implementation. This is how our spy can look like:

package net.lkrnac.blog.testing.mockbeanv2.aoptesting;

import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import lombok.Getter;
import net.lkrnac.blog.testing.mockbeanv2.beans.AddressDao;
import net.lkrnac.blog.testing.mockbeanv2.beans.AddressService;

@Primary
@Service
@Profile("UserService-aop-test")
public class AddressServiceSpy extends AddressService{
    @Getter
    private AddressService spyDelegate;
    
    @Autowired
    public AddressServiceSpy(AddressDao addressDao) {
        super(null);
        spyDelegate = Mockito.spy(new AddressService(addressDao));
    }
    
    public String getAddressForUser(String userName){
        return spyDelegate.getAddressForUser(userName);
    }
}

As we can see this spy is very similar to AddressDaoMock. But in this case real bean is using constructor injection to autowire its dependency. Therefore we’ll need to define non-default constructor and do constructor injection also. But we wouldn’t pass injected dependency into parent constructor.

To enable spying on real object, we construct new instance with all the dependencies, wrap it into Mockito spy instance and store it into spyDelegate property. We expect call of method getAddressForUser() during test, therefore we delegate this call to spyDelegate. This property can be accessed in test via getter defined by Lombok’s @Getter annotation.

Test itself would look like this:

@ActiveProfiles({"UserService-aop-test", "aop"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(AopApplication.class)
public class UserServiceAopITest {
    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;
    
    @Test
    public void testGetUserDetails() {
        // GIVEN
        AddressServiceSpy addressServiceSpy = (AddressServiceSpy) addressService;

        // WHEN
        String actualUserDetails = userService.getUserDetails("john");
  
        // THEN 
        Assert.assertEquals("User john, 3 Dark Corner", actualUserDetails);
        Mockito.verify(addressServiceSpy.getSpyDelegate()).getAddressForUser("john");
    }
}

It is very straight forward. Profile UserService-aop-test ensures that AddressServiceSpy will be scanned. Profile aop ensures same for AddressLogger aspect. When we autowire testing object UserService and its dependency AddressService, we know that we can cast it to AddressServiceSpy and verify the call on its spyDelegate property after calling the testing method.

Fake Spring bean proxied by Spring AOP

It is obvious that delegating calls into Mockito mocks or spies complicates the testing. These patterns are often overkill if we simply need to fake the logic. We can use such fake in that case:

@Primary
@Repository
@Profile("AddressService-aop-fake-test")
public class AddressDaoFake extends AddressDao{
    public String readAddress(String userName) {
        return userName + "'s address";
    }
}

and used it for testing this way:

@ActiveProfiles({"AddressService-aop-fake-test", "aop"})
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(AopApplication.class)
public class AddressServiceAopFakeITest {
    @Autowired
    private AddressService addressService; 

    @Test
    public void testGetAddressForUser() {
        // GIVEN - Spring context
 
        // WHEN 
        String actualAddress = addressService.getAddressForUser("john");
 
        // THEN  
        Assert.assertEquals("john's address", actualAddress);
    }
}

I don’t think this test needs explanation.

Source code for these examples is hosted on Github.

Why is wide usage of PowerMock problematic

There are Java constructs well known for their testability issues:

  • Private methods
  • Static methods
  • Constuctors
  • Final methods or classes

Skilled Java developer following TDD tries to minimize their testability impacts. Don’t want to dive into techniques to enhance testability. They are explained well on Misko Hevery’s blog.

Some developers argue that we have frameworks today (like PowerMock or JMockIt) that are able mock these testability killers. And it’s true. So should we throw factory methods to bin and start using static or singleton classes widely? The answer is NO. Reason is in Java language nature. There isn’t way how to mock mentioned constructs using Java features like inheritance, polymorphism or reflection. Byte-code manipulation is needed. And that is the problem.

Here are some facts about PowerMock:

  • It is using Javassist library for byte-code manipulation
  • It took 1.5 years to make PowerMock + Javaassist compatible with Java7 since its introduction. Here is note from PowerMock change log:
Change log 1.5 (2012-12-04)
---------------------------
Upgraded to Javassist 3.17.1-GA, this means that PowerMock works in Java 7!

I tried to use PowerMock and JMockIt to test some legacy code. The result weren’t acceptable for me. Sometimes there were some strange crashes or clash with JaCoCo test coverage tool (have to say that I didn’t give JMockIt deep chance and abandoned on it immediately after first problems). At the end I always decided to change the production code to enhance testability and use plain Mockito.

If it would be up to me I would exclude byte-code manipulation testing frameworks from technology stack completely. Java8 is coming soon and potential migration of unit tests can be a big problem if it is used widely. It would be ridiculous to wait 1.5 years for Java8 update because of testing framework.

I respect PowerMock and JMockIt projects and people behind them. They are sometimes valuable in cases when you have to deal with legacy code or third party libraries.

Use Mockito to mock autowired fields

EDIT: Field injections are widely considered (including myself) as bad practice. Read here for more info. I would suggest to use constructor injection instead.

Dependency injection is very powerful feature of Inversion of Control containers like Spring and EJB. It is always good idea to encapsulate injected values into private fields. But encapsulation of autowired fields decreases testability.

I like the way how Mockito solved this problem  to mock autowired fields. Will explain it on example. (This blog post expects that you are little bit familiar with Mockito syntax, but it is self-descriptive enough though.)

Here is first dependency of testing module. It is Spring singleton bean. This class will be mocked in the test.

@Repository
public class OrderDao {
	public Order getOrder(int irderId){
		throw new UnsupportedOperationException("Fail is not mocked!");
	}
}

Here is second dependency of testing class. It is also Spring component. This class will be spied (partially mocked) in test. Its method calculatePriceForOrder will be invoked unchanged. Second method will be stubbed.

@Service
public class PriceService {
	public int getActualPrice(Item item){
		throw new UnsupportedOperationException("Fail is not mocked!");
	}

	public int calculatePriceForOrder(Order order){
		int orderPrice = 0;
		for (Item item : order.getItems()){
			orderPrice += getActualPrice(item);
		}
		return orderPrice;
	}
}

And here is class under test. It  autowires dependencies above.

@Service
public class OrderService {

	@Autowired
	private PriceService priceService;

	@Autowired
	private OrderDao orderDao;

	public int getOrderPrice(int orderId){
		Order order = orderDao.getOrder(orderId);
		return priceService.calculatePriceForOrder(order);
	}
}

Finally here is test example. It uses field level annotations:

  • @InjectMocks – Instantiates testing object instance and tries to inject fields annotated with @Mock or @Spy into private fields of testing object
  • @Mock – Creates mock instance of the field it annotates
  • @Spy – Creates spy for instance of annotated field
public class OrderServiceTest {
	private static final int TEST_ORDER_ID = 15;
	private static final int TEST_SHOES_PRICE = 2;   
	private static final int TEST_SHIRT_PRICE = 1;

	@InjectMocks
	private OrderService testingObject;

	@Spy
	private PriceService priceService;

	@Mock
	private OrderDao orderDao;

	@BeforeMethod
	public void initMocks(){
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void testGetOrderService(){
		Order order = new Order(Arrays.asList(Item.SHOES, Item.SHIRT));
		Mockito.when(orderDao.getOrder(TEST_ORDER_ID)).thenReturn(order);

		//notice different Mockito syntax for spy
		Mockito.doReturn(TEST_SHIRT_PRICE).when(priceService).getActualPrice(Item.SHIRT);
		Mockito.doReturn(TEST_SHOES_PRICE).when(priceService).getActualPrice(Item.SHOES);

		//call testing method
		int actualOrderPrice = testingObject.getOrderPrice(TEST_ORDER_ID);

		Assert.assertEquals(TEST_SHIRT_PRICE + TEST_SHOES_PRICE, actualOrderPrice);
	}
}

So what happen when you run this test:

  1. First of all TestNG framework picks up @BeforeMethod annotation and invokes initMocks method
  2. This method invokes special Mockito call (MockitoAnnotations.initMocks(this)) to initialize annotated fields. Without this call, these objects would be null. Common mistake with this approach is to forget this invocation.
  3. When all the test fields are populated with desired values, test is called.

This example doesn’t include Spring context creation and Spring’s annotations are here only as examples for usage against production code. Test itself doesn’t include  any dependency to Spring and ignores all its annotations. In fact there could be used EJB annotations instead or it can be running against plain (non IoC managed) private fields.

Developers tend to think about MockitoAnnotations.initMocks(this) call as unnecessary overhead. But it is actually very handy, because it resets testing object and re-initializes mocks. You can use it for example

  • When you have various test methods using same annotated instances to ensure that various test runs doesn’t use same recorded behavior
  • When repetitive / parametrized tests are used. For example you can include this call into test  method itself and receive spy object as test parameter (as part of test case). This ability is very sexy in conjunction to TestNG @DataProvider feature (Will explain this in different blog post).

@Spy annotated object can be created in two ways

  • Automatically by Mockito framework if there is default (non-parametrized) constructor
  • Or explicitly initialized (e.g. when there is only non-default constructor)

Testing object annotated by @InjectMocks can be also initialized explicitly.

Example source code can be downloaded from GitHub.

Mock static method

Foreword

If you already read some other blog post about unusual mocking, you can skip prelude via this link.

I was asked to put together examples how to mock Java constructs well know for their testability issues:

I am calling these techniques unusual mocking. I was worried that such examples without any guidance can be widely used by teammates not deeply experienced in mocking frameworks.

Developers practicing TDD or BDD should be aware of testability problems behind these constructs and try to avoid them when designing their tests and modules. That is the reason why you probably wouldn’t be facing such unusual mocking often on project using these great programming methodologies.

But sometimes you have to extend or maintain legacy codebase that usually contains low cohesive classes. In most cases there isn’t time in current hectic agile world to make such class easy to unit test standard way. When you are trying to unit test such class you often realize that unusual mocking is needed.

That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework.

Mock static method

Refactoring considerations

  1. No mocking – In theory, static methods should be used only in small utility classes. Their functionality should be simple enough. So there shouldn’t be need to  mock static method.
  2. Converting into Spring/EJB bean – If the functionality in static method isn’t simple enough and mocking is needed, consider converting class into Spring/EJB singleton bean. Such bean can be injected into testing class. This is easily mockable by plain Mockito functionality (see this blog post).

Workaround using Mockito

This is my preferred technique when I need to mock static method. I believe that minor exposing of internal implementation in flavor to enhance testability of testing module is much lower risk for project than fall into bytecode manipulation mocking  framework like PowerMock or JMockIt.

This technique involves:

  • Encapsulation of static methods into default method
  • Partial mock (spy) is used to mock this method during testing

Mockito example covers:

  1. Mocking of encapsulated method with return value
  2. Mocking of encapsulated void method
  3. Verifying of encapsulated method calls

Class under test:

public class HumanityMockito {
	/**
	 * Is used as testing target to demostrate static mocking workaround
	 * 
	 * @param greenHouseGasesList
	 *            list of greenhouse gases amounts to release into atmosphere
	 * @return greenhouse gases levels in atmosphere
	 */
	public double revageAthmoshere(Collection<Integer> greenHouseGasesList) {
		for (int greenhouseGases : greenHouseGasesList) {
			releaseGreenHouseGases(greenhouseGases);
		}
		return monitorRevageOfAthmosphere();
	}

	/**
	 * Void method with default access modifier to be mocked. Wraps static
	 * method call.
	 * 
	 * @param volume
	 *            volume of greenhouse gases to release
	 */
	void releaseGreenHouseGases(int volume) {
		Athmosphere.releaseGreenhouseGases(volume);
	}

	/**
	 * Method with return value and default access modifier to be mocked. Wraps
	 * static method call.
	 * 
	 * @return greenhouse gases level
	 */
	double monitorRevageOfAthmosphere() {
		return Athmosphere.getGreenhouseGassesLevel();
	}
}

Test:

public class HumanityMockitoTest {
	private static final int BILION_TONS_CO2 = 5;
	private static final double GREENGOUSE_GASSES_LEVEL = 393.1;

	@Test
	public void testRevageAthmoshere() {
		HumanityMockito humanity = new HumanityMockito();
		HumanityMockito humanitySpy = Mockito.spy(humanity);

		Mockito.doReturn(GREENGOUSE_GASSES_LEVEL).when(humanitySpy)
				.monitorRevageOfAthmosphere();
		Mockito.doNothing().when(humanitySpy)
				.releaseGreenHouseGases(BILION_TONS_CO2);

		// invoke testing method
		Collection<Integer> greenHouseGassesList = new ArrayList<>(
				Arrays.asList(BILION_TONS_CO2, BILION_TONS_CO2));
		double actualLevel = humanitySpy.revageAthmoshere(greenHouseGassesList);

		Assert.assertEquals(actualLevel, GREENGOUSE_GASSES_LEVEL);
		Mockito.verify(humanitySpy, Mockito.times(greenHouseGassesList.size()))
				.releaseGreenHouseGases(BILION_TONS_CO2);
	}
}

Usage of PowerMock

Before usage of this example, please carefully consider if it is worth to bring bytecode  manipulation risks into your project. They are gathered in this blog post. In my opinion it should be used only in very rare and non-avoidable cases.

Test shows how to mock static method by PowerMock directly. Example covers:

  1. Mocking of static method with return value
  2. Mocking of static void method
  3. Verifying of static method calls

Class under test:

public class HumanityPowerMock {
	public double revageAthmoshere(Collection<Integer> greenHouseGasesList) {
		for (int greenhouseGases : greenHouseGasesList) {
			Athmosphere.releaseGreenhouseGases(greenhouseGases);
		}
		return Athmosphere.getGreenhouseGassesLevel();
	}
}

Test:

@PrepareForTest(Athmosphere.class)
public class HumanityPowerMockTest extends PowerMockTestCase {
	private static final int BILION_TONS_CO2 = 5;
	private static final double GREENGOUSE_GASSES_LEVEL = 393.1;

	@Test
	public void testRevageAthmoshere() {
		PowerMockito.mockStatic(Athmosphere.class);

		Mockito.when(Athmosphere.getGreenhouseGassesLevel()).thenReturn(
				GREENGOUSE_GASSES_LEVEL);

		// call of static method is required to mock it
		PowerMockito.doNothing().when(Athmosphere.class);
		Athmosphere.releaseGreenhouseGases(BILION_TONS_CO2);

		// invoke testing method
		Collection<Integer> greenHouseGassesList = new ArrayList<>(
				Arrays.asList(BILION_TONS_CO2, BILION_TONS_CO2));
		HumanityPowerMock humanity = new HumanityPowerMock();
		double actualLevel = humanity.revageAthmoshere(greenHouseGassesList);

		Assert.assertEquals(actualLevel, GREENGOUSE_GASSES_LEVEL);

		// call of static method is required to verify it
		PowerMockito.verifyStatic(Mockito.times(greenHouseGassesList.size()));
		Athmosphere.releaseGreenhouseGases(BILION_TONS_CO2);
	}
}

Links

Source code can be downloaded from Github.

Other unusual mocking examples:

Mock constructor

Foreword

If you already read some other blog post about unusual mocking, you can skip prelude via this link.

I was asked to put together examples how to mock Java constructs well know for their testability issues:

I am calling these techniques unusual mocking. I was worried that such examples without any guidance can be widely used by teammates not deeply experienced in mocking frameworks.

Developers practicing TDD or BDD should be aware of testability problems behind these constructs and try to avoid them when designing their tests and modules. That is the reason why you probably wouldn’t be facing such unusual mocking often on project using these great programming methodologies.

But sometimes you have to extend or maintain legacy codebase that usually contains low cohesive classes. In most cases there isn’t time in current hectic agile world to make such class easy to unit test standard way. When you are trying to unit test such class you often realize that unusual mocking is needed.

That is why I decided to create and share refactoring considerations alongside with examples and workarounds for unusual mocking. Examples are using Mockito and PowerMock mocking frameworks and TestNG unit testing framework.

Mock constructor

Refactoring considerations

  • If your testing method creates instance/s of some type, there are two possibilities what can happen with these instances
    • Created instance/s are returned from testing method. They are in this case part of the testing method API. This can be tested by verifying against created instances rather than constructor method call. If target instances doesn’t have hashCode/equals contract implemented, you can still create test specific comparator to verify created data.
    • Created instances are used as parameter/s passed to some dependency object. This dependency object of testing class is most probably mocked. In this case it’s better idea to capture arguments of dependency method call and verify them. Mockito offers good support for this.
    • Created instances are temporary objects that support testing method job. In this case you shouldn’t care about creation of these instances, because you should treat testing module as black box that doing the job, but you don’t know how.
  • Create factory class for constructing instances and mock it standard way.
  • If that fits to requirement -> Abstract factory design pattern

Workaround using Mockito

This is my preferred technique when I need to mock constructor. I believe that minor exposing of internal implementation in flavor to enhance testability of testing module is much lower risk for project than fall into bytecode manipulation mocking  framework like PowerMock or JMockIt.

This technique involves:

  • Encapsulating the constructor into method with default access modifier
  • Partial mock (spy) is used to mock this method during testing

Mockito example covers:

  1. Partial mocking of factory method
  2. Verifying of mocked factory method call

Class under test:

public class CarFactoryMockito {
	Car carFactoryMethod(String type, String color) {
		return new Car(type, color);
	}

	public Car constructCar(String type, String color) {
		carFactoryMethod(type, color);
		// ... other logic needed to be tested ...
		return carFactoryMethod(type, color);
	}
}

Test:

public class CarFactoryMockitoTest {
	private static final String TESTING_TYPE = "Tatra";
	private static final String TESTING_COLOR = "Black";

	@Test
	public void testConstructCar() {
		CarFactoryMockito carFactory = new CarFactoryMockito();
		CarFactoryMockito carFactorySpy = Mockito.spy(carFactory);

		Car mockedInstance = Mockito.mock(Car.class);
		Mockito.doReturn(mockedInstance).when(carFactorySpy)
				.carFactoryMethod(TESTING_TYPE, TESTING_COLOR);

		// invoke testing method
		Car actualInstance = carFactorySpy.constructCar(TESTING_TYPE,
				TESTING_COLOR);

		Assert.assertEquals(actualInstance, mockedInstance);
		// ... verify other logic in constructCar() method ...
		Mockito.verify(carFactorySpy, Mockito.times(2)).carFactoryMethod(
				TESTING_TYPE, TESTING_COLOR);
	}
}

Usage of PowerMock

Before usage of this example, please carefully consider if it is worth to bring bytecode  manipulation risks into your project. They are gathered in this blog post. In my opinion it should be used only in very rare and non-avoidable cases.

Test shows how to mock constructor directly by PowerMock. Example covers:

  1. Mocking of constructor
  2. Verifying of constructor call

Class under test:

public class CarFactoryPowerMock {
	public Car constructCar(String type, String color) {
		new Car(type, color);
		return new Car(type, color);
	}
}

Test:

/**
 * Demonstrates constructor mocking by PowerMock.
 * <p>
 * NOTE: Prepared in PowerMock annotation {@link PrepareForTest} should be class
 * where is constructor called
 */
@PrepareForTest(CarFactoryPowerMock.class)
public class CarFactoryPowerMockTest extends PowerMockTestCase {
	private static final String TESTING_TYPE = "Tatra";
	private static final String TESTING_COLOR = "Black";

	@Test
	public void testConstructCar() throws Exception {
		Car expectedCar = Mockito.mock(Car.class);
		PowerMockito.whenNew(Car.class)
				.withArguments(TESTING_TYPE, TESTING_COLOR)
				.thenReturn(expectedCar);

		// invoke testing method
		CarFactoryPowerMock carFactory = new CarFactoryPowerMock();
		Car actualCar = carFactory.constructCar(TESTING_TYPE, TESTING_COLOR);

		Assert.assertEquals(actualCar, expectedCar);
		// ... verify other logic in constructCar() method ...
		PowerMockito.verifyNew(Car.class, Mockito.times(2)).withArguments(
				TESTING_TYPE, TESTING_COLOR);
	}
}

Links

Source code can be downloaded from Github.

Other unusual mocking examples: