【发布时间】:2018-12-27 13:01:09
【问题描述】:
注意:这是我在这里的第一篇文章,请原谅任何遗漏的信息或真正的新手问题。
所以我目前正在尝试为已经完成的使用 spring 的 Web 应用程序编写 jUnit 测试(一切正常,我只需要完全覆盖测试)。 我有类:“Employee”、“EmployeeController”和“EmployeeManagement”。 我想测试“registerNew”函数,如果它没有错误(“错误结果”),它会使用填写的表单“EmployeeRegistrationForm”创建一个新员工。
现在我想为此编写一个测试,以确保该函数确实创建了一个新对象“Employee”,该对象应使用所述表单保存在“EmployeeRepository”中。
但是,我似乎无法创建一个填充的“EmployeeForm”,因为它是抽象的并且无法实例化。因此,我正在努力为该函数提供任何论据,并且不知道如何将测试所需的信息传递给正在测试的函数。
@Service
@Transactional
public class EmployeeManagement {
private final EmployeeRepository employees;
private final UserAccountManager userAccounts;
EmployeeManagement(EmployeeRepository employees, UserAccountManager userAccounts) {
Assert.notNull(employees, "employeeRepository must not be null!");
Assert.notNull(userAccounts, "UserAccountManager must not be null!");
this.employees=employees;
this.userAccounts = userAccounts;
}
//the function that creates the employee
public Employee createEmployee(EmployeeRegistrationForm form) {
Assert.notNull(form, "Registration form must not be null!");
String type = form.getType();
Role role = this.setRole(type);
UserAccount useraccount = userAccounts.create(form.getUsername(), form.getPassword(), role);
useraccount.setFirstname(form.getFirstname());
useraccount.setLastname(form.getLastname());
return employees.save(new Employee(form.getNumber(), form.getAddress(), useraccount));
}
@Controller
public class EmployeeController {
private final EmployeeManagement employeeManagement;
EmployeeController(EmployeeManagement employeeManagement) {
Assert.notNull(employeeManagement, "userManagement must not be null!");
this.employeeManagement = employeeManagement;
}
@PostMapping("/registerEmployee")
@PreAuthorize("hasRole('ROLE_ADMIN')")
String registerNew(@Valid EmployeeRegistrationForm form, Errors result) {
if (result.hasErrors()) {
return "registerEmployee";
}
employeeManagement.createEmployee(form);
return "redirect:/";
}
public interface EmployeeRegistrationForm {
@NotEmpty(message = "{RegistrationForm.firstname.NotEmpty}")
String getFirstname();
@NotEmpty(message = "{RegistrationForm.lastname.NotEmpty}")
String getLastname();
@NotEmpty(message = "{RegistrationForm.password.NotEmpty}")
String getPassword();
@NotEmpty(message = "{RegistrationForm.address.NotEmpty}")
String getAddress();
@NotEmpty(message = "{RegistrationForm.number.NotEmpty}")
String getNumber();
@NotEmpty(message = "{RegistrationForm.type.NotEmpty}")
String getType();
@NotEmpty(message = "{RegistrationForm.username.NotEmpty}")
String getUsername();
}
【问题讨论】:
-
会有一些类在你的应用程序中扩展
EmployeeRegistrationForm
标签: java forms spring-mvc junit controller