Share this blog!

How to use Mockito ArgumentCaptor in tests



Mockito has a list of uniquely useful components and ArgumentCaptor is one such example. 


As the name suggests, ArgumentCaptor can be used to examine arguments passed onto methods, which cannot be accessed otherwise. 


Let's assume we have a Util class as follows that simply prints whatever String argument is passed onto it. 


public class Util {

public void shoutOut(String lifeQuote) {
System.out.println(lifeQuote);
}
}


Then let's assume we have another class Dog that will be calling the Util's method:


public class Dog {

private Util util;

public Dog(Util util) {
this.util = util;
}

public void bark() {
String lifeQuote = "I'm awesome";
this.util.shoutOut(lifeQuote);
}
}


In this kind of scenario, we wouldn't have a way to test if the method shoutOut actually prints the desired life quote.


This is where ArgumentCaptor becomes useful as follows.

Some important points to notice:
  • The object Util needs to be mocked since the argument to be tested is passed onto a method in it
  • The ArgumentCaptor needs to be instantiated using the object type of the argument that is to be tested
  • The verify method should be called on the mocked object

import junit.framework.TestCase;
import org.junit.Test;
import org.mockito.ArgumentCaptor;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class DogTest extends TestCase {

@Test
public void testBark() {

// The argument to be tested should be called on a mocked class
// i.e. we need to test the "lifeQuote" argument passed onto "Util" method "shoutOut"
// therefore we should mock the Util class
Util utilMock = mock(Util.class);

Dog toby = new Dog(utilMock);
toby.bark();

// We need to create a captor to capture the argument
// In our case, the captured argument is of type String
ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);

// Verify that the captor is used in the mocked method
verify(utilMock).shoutOut(captor.capture());

// Retrieve the captured value
String updatedLifeQuote = captor.getValue();

// Assert if the value is as expected
assertEquals("I'm awesome", updatedLifeQuote);
}

}

Cheers!
Next PostNewer Post Previous PostOlder Post Home

1 comment:

  1. emperor casino
    emperor casino - Full Tilt Poker Tilt - 100% Deposit Bonus up to €400 - €500 Casino Bonus - Play 제왕카지노 가입 at Play Online Poker for Free! The best online casino in the world to play with a

    ReplyDelete