PDA

View Full Version : white box testing controllers



jburns
Aug 24th, 2004, 12:52 PM
what's the best way to get a SecureContext in unit tests? I'm using auth.getPrincipal()).getUsername() to do some queries based on the username in a controller, and would like to test it by a mock, or another method. I have httpunit tests working just fine as an outside view.

// from acegi sample app
Authentication auth = ((SecureContext) ContextHolder.getContext()).getAuthentication();
String owner = auth.getPrincipal().toString();

if (auth.getPrincipal() instanceof UserDetails) {
owner = ((UserDetails) auth.getPrincipal()).getUsername();
}
// end

(...)

User currentuser = usermgr.getUserByUsername(owner);
project.setOwner(currentuser);
mgr.saveProject(project);

Ben Alex
Aug 24th, 2004, 04:38 PM
Your code block looks fine. As you said, it's the way Acegi Security code approaches it in unit tests.

Having said that, unit tests should be testing a specific class at a time. So as a rule of thumb, unit tests (outside the Acegi Security project itself) should only be calling the ContextHolder etc if the class under test actually uses it for business logic.

In relation to mocking the ContextHolder itself, that would be difficult as your business class would be calling that class expressly. If was a real issue you could have a protected method in your class to return the username or Authentication or whatever level of granularity your business class requires from the ContextHolder. Then you could override that protected method in a unit test. Don't forget you could alternatively provide a mock SecureContext and drop it into the ContextHolder during the test.

jburns
Aug 24th, 2004, 10:03 PM
good point, thanks for the direction!