While you test using mocks it would be necessary sometime to capture the arguments passed into mocked behavior. JMockit Verification.withCapture method can be used to capture the argument passed into a mocked behavior.
The complete source code for this article can be found in the github
package com.ourownjava.tdd.mockit; import javax.naming.AuthenticationException; /** * * @author Sanju Thomas * */ public class AuthenticationManager { private ThridPartyAuthenticationService authenticationService; public void authenticate(final Principal pricipal) throws AuthenticationException{ if(!authenticationService.authenticate(pricipal)){ throw new AuthenticationException("I think we haven't met yet! did we?"); } } }
package com.ourownjava.tdd.mockit; /** * * @author Sanju Thomas * */ public class ThridPartyAuthenticationService { /** * Not yet implemented. * * @param pricipal * @return */ public boolean authenticate(Principal pricipal) { return false; } }
package com.ourownjava.tdd.mockit; /** * * @author Sanju Thomas * */ public class Principal { public Principal(final String loginId){ this.loginId = loginId; } private String loginId; public String getLoginId() { return loginId; } }
package com.ourownjava.tdd.jmockit; import static org.junit.Assert.assertEquals; import javax.naming.AuthenticationException; import mockit.Deencapsulation; import mockit.Injectable; import mockit.NonStrictExpectations; import mockit.Verifications; import org.junit.Before; import org.junit.Test; import com.ourownjava.tdd.mockit.AuthenticationManager; import com.ourownjava.tdd.mockit.Principal; import com.ourownjava.tdd.mockit.ThridPartyAuthenticationService; /** * * @author Sanju Thomas * */ public class TestAuthenticationManager { private AuthenticationManager authenticationManager; @Injectable private ThridPartyAuthenticationService thridPartyAuthenticationService; @Before public void setUp(){ authenticationManager = new AuthenticationManager(); Deencapsulation.setField(authenticationManager, "authenticationService", thridPartyAuthenticationService); } @Test public void shouldNotAuthenticate() throws AuthenticationException{ new NonStrictExpectations() {{ thridPartyAuthenticationService.authenticate((Principal) any); returns(true); }}; final Principal pricipal = new Principal("thegoodguy"); authenticationManager.authenticate(pricipal); new Verifications() {{ Principal vPrincipal; thridPartyAuthenticationService.authenticate(vPrincipal = withCapture()); assertEquals("thegoodguy", vPrincipal.getLoginId()); }}; } }