JAAS / Kerberos stub with Mockito
- Mockito JAAS stub
- Mock JAAS Mockito
- JAAS unit tests
- Mockito Kerberos stub
- Mock Kerberos Mockito
- Kerberos unit tests
Suppose we 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 output:
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 testedWithoutJaas instance in the unit test:
@Test
public void xTest() {
// ...
// <preparing testedWithoutJaas instance>
// ...
String actual = testedWithoutJaas.x();
String expected = "123";
assertEquals(expected, actual);
}