我正在为我的代码编写单元测试。现在我想测试放入表单的值是否正确保存在Controller中的变量中。依赖于此模型属性的两个测试都是正确的,都会失败。因为模型存在但保持为null,这必然意味着我以错误的方式从我的测试中发送值。如何让我的测试包含输入值以正确测试post方法?
测试testPostValueInModel()失败,出现AssertionError:
java.lang.AssertionError: Model attribute 'chosenTemp' does not exist
我必须注意到我对这一切都很陌生,所以如果有人有答案,请提供更多代码示例并解释出现了什么问题,以便我可以从错误中吸取教训。谢谢。
这是我的测试类:
@RunWith(SpringRunner.class)
@WebMvcTest(InvoerschermController.class)
@AutoConfigureMockMvc
public class InvoerschermTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testCorrectModel() {
try {
this.mockMvc.perform(get("/invoer", "20")).andExpect(status().isOk())
.andExpect(model().attributeExists("chosenTemp"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPost() {
try {
this.mockMvc.perform(post("/invoer", "20")).andExpect(status().isOk())
.andExpect(view().name("invoerscherm"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPostValueInModel() {
try {
this.mockMvc.perform(post("/invoer", "20")).andExpect(status().isOk())
.andExpect(model().attributeExists("chosenTemp"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
控制器:
@Controller
public class InvoerschermController {
private String chosenTemp = "20";
private static PostgresDatabase database;
private static Connection connection;
// Static initializer for the database
static {
database = new PostgresDatabase();
connection = database.connectToDatabase();
}
@GetMapping("/invoer")
public String invoer(Model model) {
// int newTemp = Integer.parseInt(getChosenTemp());
chosenTemp = database.getTemperature(connection);
model.addAttribute("chosenTemp", getChosenTemp());
return "invoerscherm";
}
@PostMapping("/invoer")
public String addInputTemp(String chosenTemp, Model model) {
setChosenTemp(chosenTemp);
model.addAttribute("chosenTemp", getChosenTemp());
try {
int newTemp = Integer.parseInt(getChosenTemp());
database.setTemperature(connection, newTemp);
} catch (NumberFormatException nfe) {
System.err.println("Invalid number: " + nfe.getMessage());
}
return "invoerscherm";
}
public String getChosenTemp() {
return chosenTemp;
}
public void setChosenTemp(String chosenTemp) {
this.chosenTemp = chosenTemp;
}
}
The Thymeleaf:
<!DOCTYPE HTML>
<html xmlns:th="http://www.thymeleaf.org">
<head th:include="fragments/template :: head"></head>
<head>
<title>Smart CV</title>
</head>
<body>
<nav th:replace="fragments/template :: header"></nav>
<div class="container">
<div class="hero-unit">
<h1>Temperatuur instellen</h1>
</div>
<form action="#" th:action="@{/invoer}" th:object="${invoerscherm}"
method="post">
<div class="form-group">
<label for="chosenTemp">Gewenste temperatuur:</label> <input
type="text" class="form-control" id="chosenTemp" name="chosenTemp"
autocomplete="off" th:value="${chosenTemp}" />
</div>
<button type="submit" class="btn btn-default" name="submitKnop">Stel
in</button>
</form>
</div>
<nav th:replace="fragments/template :: footer"></nav>
</body>
</html>
答案 0 :(得分:1)
首先,你的控制器存在缺陷。你不应该保持本地状态(试着想象当3个用户同时提交时chosenTemp
字段会发生什么,因为InvoerschermController
只有一个实例。
您的方法参数应使用@RequestParam("chosenTemp")
进行注释,以匹配您发送的表单。您的测试还应反映您发送名为chosenTemp
的参数的事实。
首先是您的控制器
@Controller
public class InvoerschermController {
private static PostgresDatabase database;
private static Connection connection;
// Static initializer for the database
static {
database = new PostgresDatabase();
connection = database.connectToDatabase();
}
@GetMapping("/invoer")
public String invoer(Model model) {
Integer chosenTemp = database.getTemperature(connection);
model.addAttribute("chosenTemp", chosenTemp);
return "invoerscherm";
}
@PostMapping("/invoer")
public String addInputTemp(@RequestParam("chosenTemp") Integer chosenTemp, Model model) {
model.addAttribute("chosenTemp", chosenTemp);
database.setTemperature(connection, chosenTemp);
return "invoerscherm";
}
}
注意从String
到Integer
的类型更改Spring将为您进行类型转换,并注意添加@RequestParam
。现在你的测试也应该反映出来。
@RunWith(SpringRunner.class)
@WebMvcTest(InvoerschermController.class)
@AutoConfigureMockMvc
public class InvoerschermTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testCorrectModel() {
try {
this.mockMvc.perform(get("/invoer")).andExpect(status().isOk())
.andExpect(model().attributeExists("chosenTemp"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPost() {
try {
this.mockMvc.perform(post("/invoer").param("chosenTemp", "20").andExpect(status().isOk())
.andExpect(view().name("invoerscherm"));
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testPostValueInModel() {
try {
this.mockMvc.perform(post("/invoer").param("chosenTemp", "20")).andExpect(status().isOk())
.andExpect(model().attributeExists("chosenTemp"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
注意添加.param("chosenTemp", "20")
以添加具有该名称的请求参数。
你的控制器仍然存在缺陷,因为它不应该关心应该在你的Connection
课程中封装的Database
。虽然您的测试现在可能正常,但由于使用了Thymeleaf和表单绑定,您的实际应用程序仍然会失败。表单绑定要求键invoerScherm
下的对象可用,并且该对象应具有名为chosenTemp
的属性。你实际上缺少一个表单对象。那么你的控制器应该是什么样的。
首先你需要一个表单对象:
public class InvoerScherm {
private Integer chosenTemp;
public InvoerScherm() {}
public InvoerScherm(Integer temp) { this.chosenTemp=temp;}
// Here be getters/setters
}
然后让你的控制器创建并使用它
@Controller
public class InvoerschermController {
private static PostgresDatabase database;
private static Connection connection;
// Static initializer for the database
static {
database = new PostgresDatabase();
connection = database.connectToDatabase();
}
@GetMapping("/invoer")
public String invoer(Model model) {
Integer chosenTemp = database.getTemperature(connection);
InvoerScherm invoerScherm = new InvoerScherm(chosenTemp);
model.addAttribute("invoerScherm", invoerScherm);
return "invoerscherm";
}
@PostMapping("/invoer")
public String addInputTemp(@ModelAttribute InvoerScherm invoerScherm, Model model) {
database.setTemperature(connection, invoerScherm.getChosenTemp());
return "invoerscherm";
}
}
当然,现在你的测试会再次失败,但我把这个任务留给你了。