Announcement Announcement Module
No announcement yet.
white box testing controllers Page Title Module
Move Remove Collapse
This topic is closed
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • white box testing controllers

    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);

  • #2
    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.


    • #3
      good point, thanks for the direction!