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

佐手、 提交于 2019-12-11 01:19:58

问题


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

回答1:


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.




回答2:


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(...);
}



回答3:


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


来源:https://stackoverflow.com/questions/2456810/how-do-you-set-a-custom-session-when-unit-testing-with-wicket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!