开发者

How do you set a custom session when unit testing with wicket?

I'm trying to run some unit tests on a wicket page that only allows access after you've logged in. In my JUnit test I cannot start the page or render it without setting the session.

How do you set the session? I'开发者_C百科m having problems finding any documentation on how to do this.

    WicketTester tester = new WicketTester(new MyApp());
((MyCustomSession)tester.getWicketSession()).setItem(MyFactory.getItem("abc"));

//Fails to start below, no session seems to be set
    tester.startPage(General.class);
tester.assertRenderedPage(General.class);


What I frequently do is to provide a fake WebApplication with overrides for things that I want to mock or stub.

Among the things I override is the method

    public abstract Session newSession(Request request, Response response);

which allows you to return a fake session setup with anything you want.

This is in Wicket 1.3 - if you're using 1.4, some of this may have changed, and as noted in another response, it may be related to a wicket bug.

But assuming the interface hasn't changed too much, overriding this method may also be another way of working around the issue in WICKET-1215.


You may be running into WICKET-1215. Otherwise what you're doing looks fine. For example, I have a Junit4 setup method that looks like:

@Before
public void createTester() {
    tester = new WicketTester( new MyApp() );
    // see http://issues.apache.org/jira/browse/WICKET-1215
    tester.setupRequestAndResponse();
    MyAppSession session = (MyAppSession) tester.getWicketSession();
    session.setLocale(Locale.CANADA);
    session.setUser(...);
}


Using Wicket 1.4, I use my normal WebApplication and WebSession implementations, called NewtEditor and NewtSession in my app. I override newSession, where I do the same than in the regular app code, except that I sign in right away. I also override newSessionStore for performance reasons, I copied this trick from WicketTesters code.

tester = new WicketTester(new NewtEditor() 
{
    @Override
    public Session newSession(Request request, Response response)
    {
        NewtSession session = new NewtSession(request);
        session.signIn(getTestDao());
        return session;
    }

    @Override
    protected ISessionStore newSessionStore()
    {
        // Copied from WicketTester: Don't use a filestore, or we spawn lots of threads,
        // which makes things slow.
        return new HttpSessionStore(this);
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜