Search code examples
javaunit-testingjuniteasymockshiro

How to mock a shirosession?


In my project shiro session is used to authenticate users.I am to write a mock test for a service call. i.e.
object.setCreatedBy(SecurityUtils.getSubject().getPrincipal().toString())
which sets loggedin user (such as sandy) in CreatedBy field .Now I want to populate this value from testCase(using Junit 4.0 and easy 3.0).I am using following code

public class ExampleShiroUnitTest extends AbstractShiroTest {

@Test
public void testSimple() {
    //1.  Create a mock authenticated Subject instance for the test to run:
    Subject subjectUnderTest = createNiceMock(Subject.class);
    expect(subjectUnderTest.isAuthenticated()).andReturn(true);

    //2. Bind the subject to the current thread:
    setSubject(subjectUnderTest);
}

@After
public void tearDownSubject() {
    //3. Unbind the subject from the current thread:
    clearSubject();
}

}

given at http://shiro.apache.org/testing.html. In above method subject is set properly and gives proper value when get,but don't know how to get principal out of this. When I access it from subject it return null and there is no method as setPrincipal().


Solution

  • I may be misunderstanding your question, but doesn't something like this solve the issue?

    expect(subjectUnderTest.getPrincipal()).andReturn("sandy");