I am trying to write a unit test for a guest user account. The code under test checks guest by calling this method, which in Unit Test returns null for the guest account.
/**
* Determines if the user is a guest account.
*
* @return True if the account is guest account, false otherwise.
*/
public boolean isGuest() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null) {
if (auth instanceof AnonymousAuthenticationToken) {
return true;
} else {
return false;
}
} else {
return false;
}
}
In the server Tomcat container, the anonymous user is okay it returns an instance of AnonymousAuthenticationToken
. Because the container environment & unit test environment both share the same security configuration class, assume the security config is probably correct.
The test code below also works with the MockUser
so I also think the security test configuration is probably okay:
@Test
@WithMockUser(username="Test.Customer.1@mailinator.com", roles = {"ADMIN"})
public void testCheckoutPage() throws Exception{
logger.entry();
String targetView = OrderViews.convertViewReference(getPageDirectory(), OrderViews.CHECKOUT_LOGIN_PAGE, false);
String targetUrl = "/checkout";
Order order = OrderBuilder.buildSampleGuestOrder(OrderStatus.NEW, 5);
prepareMocks(order);
Map<String, Object> sessionAttrs = new HashMap<>();
sessionAttrs.put(OrderConstants.OPEN_ORDER_ID_ATTRIBUTE, order.getId());
this.mockMvc.perform(get(targetUrl).sessionAttrs(sessionAttrs))
.andExpect(status().isOk())
.andExpect(view().name(targetView))
.andExpect(model().attribute("order", order))
.andExpect(model().attributeExists("loginForm"));
this.mockMvc.perform(MockMvcRequestBuilders.post(targetUrl))
.andExpect(status().isMethodNotAllowed());
logger.exit();
}
Does anyone have an idea how to simulate the anonymous authentication token in Unit Test?