JAAS / Kerberos / Digest stub with Mockito

You need to test the functionality of method X. It does the following things:

  • Performs authentication using JAAS;
  • If authentication is successful, it continues to work.

It’s often problematic to set up a working authentication mechanism in a unit test environment. One solution to the problem is to set a stub on the login() method of the LoginContext class.

Let’s say we have a class Tested that contains a method X:

class Tested {
	public String x() {
		LoginContext lc = new LoginContext(<special_parameters>);
		lc.login();
		...
		<tested_functionality>
		...
	}
}

Connecting Mockito for maven:

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>2.16.0</version>
    <scope>test</scope>
</dependency> 

For gradle:

testCompile group: 'org.mockito', name: 'mockito-core', version: '2.16.0'

It will not be possible to control the created object of the LoginContext class in the current implementation of method X. Let’s move this creation into a new method createLoginContext(…) of the Tested class:

class Tested {
	public String x() {
		LoginContext lc = createLoginContext(<special_parameters>);
		lc.login();
		...
		<tested_functionality>
		...
	}

	public LoginContext createLoginContext(<special_parameters>) {
		...
	}
}

In the unit test, we will use the createLoginContext(…) method and modify its “exhaust”:

Tested tested = new Tested();
LoginContext loginContextWithoutJaas = Mockito.spy(tested.createLoginContext(...));
Mockito.doNothing().when(loginContextWithoutKerberos).login();

It remains to make a modified copy of Tested, where the createLoginContext() method returns the modified LoginContext:

Tested testedWithoutJaas = Mockito.spy(tested);
Mockito.when(testedWithoutJaas.createLoginContext()).thenReturn(loginContextWithoutJaas);

Next, you can use testedWithoutJass instance in the unit test:

@Test 
public void xTest() {
    ...
    <preparing testedWithoutJaas instance>
    ...
    String actual = testedWithoutJaas.x();
    String expected = "123";
    assertEquals(expected, actual);
}

If you still have any questions, feel free to ask me in the comments under this article, or write me on promark33@gmail.com.

If I saved your day, you can support me :)

Leave a Reply

Your email address will not be published.