使用 WicketTester 时,访问会话的属性会抛出 NullPointerException 错误

Accessing attributes of session throws NullPointerException error, when using WicketTester

使用 WicketTester 时,访问会话的属性会抛出 NullPointerException 错误。

之前也有人问过类似的问题

他们建议使用的讨论

tester.getRequest().getSession().setAttribute("userName", "测试用户1");

而不是

tester.getHttpSession().setAttribute("用户名", "测试用户1");

进行该更改并没有解决问题。 可以在 github.com/rjngshn/WicketTesterSession

找到使用 'wicket.apache.org/start/quickstart.html' 创建的完整项目
    public class TestHomePage
{
    private WicketTester tester;

    @BeforeEach
    public void setUp()
    {
        tester = new WicketTester(new RTApplication());
    }
// 
    @Test
    public void userPageRendersSuccessfully()
    {
        System.out.println("Testing userPageRendersSuccessfully ");
        tester.getRequest().getSession().setAttribute("userName", "Test user 1");
        System.out.println("Uesr name in session:" + tester.getHttpSession().getAttribute("userName"));
        //start and render the test page
        tester.startPage(UserPage.class);
        //assert rendered page class
        tester.assertRenderedPage(UserPage.class);
        tester.assertModelValue("txtUserName", "Test user 1");
        System.out.println("Complete testing userPageRendersSuccessfully ");
    }
}

错误是:

 [WARN] [stderr] java.lang.NullPointerException
 [WARN] [stderr]    at uk.ac.ox.ndph.ckb.UserPage.onInitialize(UserPage.java:19)
 [WARN] [stderr]    at org.apache.wicket.Component.fireInitialize(Component.java:883)
 [WARN] [stderr]    at org.apache.wicket.MarkupContainer.internalInitialize(MarkupContainer.java:1045)

...

diff --git ResearchTracker/src/test/java/uk/ac/ox/ndph/ckb/TestHomePage.java ResearchTracker/src/test/java/uk/ac/ox/ndph/ckb/TestHomePage.java
index 757269f..a9df941 100644
--- ResearchTracker/src/test/java/uk/ac/ox/ndph/ckb/TestHomePage.java
+++ ResearchTracker/src/test/java/uk/ac/ox/ndph/ckb/TestHomePage.java
@@ -21,8 +21,8 @@ public class TestHomePage
     public void userPageRendersSuccessfully()
     {
         System.out.println("Testing userPageRendersSuccessfully ");
-        tester.getRequest().getSession().setAttribute("userName", "Test user 1");
-        System.out.println("Uesr name in session:" + tester.getHttpSession().getAttribute("userName"));
+        tester.getSession().setAttribute("userName", "Test user 1");
+        System.out.println("Uesr name in session:" + tester.getSession().getAttribute("userName"));
         //start and render the test page
         tester.startPage(UserPage.class);
         //assert rendered page class

您似乎混淆了 Wicket Session (org.apache.wicket.Session) 和 HttpSession。 在测试中,您在 HttpSession 上设置了属性,而在 UserPage 中,您试图从 Wicket Session 中读取它。