首页 > 解决方案 > 如何将对象作为参数传递给 Html 单元驱动程序

问题描述

我必须使用 Html 单元驱动程序测试网页,但是当我在没有将类对象作为参数传递的情况下获取页面时收到错误消息。

这是html代码:

<form name="fund_form" id="fund_form"  th:action="@{/save-fund}"
            th:object="${fund}" method="post">
            <input type="hidden" th:field="*{id_fund}"> <input
                type="hidden" th:value="${activeId}" th:name="owner" th:id="owner" />
            <input type="hidden" th:value="${0}" th:name="money" th:id="money" />
            <input type="hidden" th:value="${1}" th:name="state" th:id="state" />
            <textarea rows="3" cols="45" th:field="*{subject}" maxlength="135" form="fund_form" required></textarea>
            <br>
            <input type="submit" 
name="btn_save_fund" value="Insert NEW FUND!">

在这里,我将“主题”写入文本区域并使用按钮发布

这是webController的代码:

@PostMapping("/save-fund")
public String saveFund(Fund fund, Model model, 
@ModelAttribute("user") User user) {

    fundService.insertNewFund(fund);
    return myFunds(model, user);

}

在这里,我将 Active User (@ModelAttribute User) 作为参数传递给 myFunds 方法,该方法重新加载插入资金的页面。

现在我必须测试 textarea 和按钮

这是测试的代码:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class FundWebControllerIT {

@Autowired
FundRepo fundRepo;

@LocalServerPort
private int port;

private WebDriver driver;
private String baseURL;

@Before
public void setUp() throws Exception {
    baseURL = "http://localhost:" + port;
    driver = new HtmlUnitDriver();
    fundRepo.deleteAll();
    fundRepo.flush();
}

@After
public void tearDown() throws Exception {
    driver.quit();
}

//method to test (when I should pass an "user" obj as parameter
@Test
public void testInsertNewFund()  {

    driver.get(baseURL + "/my-funds");

    driver.findElement(By.id("subject")).sendKeys("test fund");
    driver.findElement(By.name("btn_save_fund")).click();

}

}

当我运行测试时,我收到此错误:

java.lang.NullPointerException: null
    at 

com.crowdfunding.controller.ApplicationWebController.myFunds(ApplicationWebController.java:50) ~[classes/:na] at com.crowdfunding.controller.ApplicationWebController.ActionMyFunds(ApplicationWebController.java:104) ~[classes/:na]

这是因为“用户”参数在

return myFunds(model, user);

一片空白。

如何在 HTML 单元测试中将对象作为参数传递?

谢谢

标签: seleniumunit-testinghtmlunit

解决方案


推荐阅读