Results 1 to 3 of 3

Thread: white box testing controllers

  1. #1
    Join Date
    Aug 2004
    Posts
    10

    Default 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);
    project.setOwner(currentuser);
    mgr.saveProject(project);

  2. #2
    Join Date
    Aug 2004
    Location
    Sydney, Australia
    Posts
    2,768

    Default

    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. #3
    Join Date
    Aug 2004
    Posts
    10

    Default

    good point, thanks for the direction!

Similar Threads

  1. help with testing controllers
    By pir8ped in forum Web
    Replies: 9
    Last Post: Apr 28th, 2006, 06:13 PM
  2. Replies: 6
    Last Post: Dec 14th, 2005, 01:28 PM
  3. Replies: 1
    Last Post: Feb 11th, 2005, 06:58 AM
  4. Unit testing protected Controllers
    By hneiper in forum AOP
    Replies: 2
    Last Post: Dec 9th, 2004, 03:29 PM
  5. Replies: 2
    Last Post: Dec 2nd, 2004, 08:57 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •