Here are the examples of the java api org.springframework.validation.BindingResult.hasFieldErrors() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
53 Examples
18
View Source File : RequestValidator.java
License : MIT License
Project Creator : njuro
License : MIT License
Project Creator : njuro
/**
* Validates JSR 303 annotations on given bean
*
* @param target object to validate
* @throws FormValidationException if validation fails
*/
public void validate(Object target) {
BindingResult bindingResult = new BeanPropertyBindingResult(target, "request");
validator.validate(target, bindingResult);
if (bindingResult.hasFieldErrors()) {
throw new FormValidationException(bindingResult);
}
}
17
View Source File : WordCountValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testInvalid_exceedsLimit() {
String testValue = String.join(" ", nCopies(501, "word"));
formInputResponse.setValue(testValue);
validator.validate(formInputResponse, bindingResult);
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(1, bindingResult.getErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("value"));
replacedertEquals("validation.field.max.word.count", bindingResult.getFieldError("value").getCode());
replacedertEquals(500, bindingResult.getFieldError("value").getArguments()[1]);
}
16
View Source File : BaseController.java
License : MIT License
Project Creator : lynnlovemin
License : MIT License
Project Creator : lynnlovemin
/**
* 参数的合法性校验
* @param result
*/
protected void validate(BindingResult result) {
if (result.hasFieldErrors()) {
List<FieldError> errorList = result.getFieldErrors();
errorList.stream().forEach(item -> replacedert.isTrue(false, item.getDefaultMessage()));
}
}
16
View Source File : IdentitiesEndpoint.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@RequestMapping(path = "/{uuid}/preplacedword", method = RequestMethod.PUT)
public ResponseEnreplacedy<Void> changePreplacedword(@PathVariable final UUID uuid, @Valid @RequestBody final ChangePreplacedword change, BindingResult bindingResult) throws InvalidPreplacedwordException {
if (bindingResult.hasFieldErrors("preplacedword")) {
throwExceptionOnInvalidPreplacedword(bindingResult);
}
updateService.changePreplacedword(uuid, change.getPreplacedword());
return ResponseEnreplacedy.ok().build();
}
16
View Source File : BaseController.java
License : Apache License 2.0
Project Creator : ash-ali
License : Apache License 2.0
Project Creator : ash-ali
/**
* 接口输入参数合法性校验
*
* @param result
*/
protected void validate(BindingResult result) {
if (result.hasFieldErrors()) {
List<FieldError> errorList = result.getFieldErrors();
errorList.stream().forEach(item -> replacedert.isTrue(false, item.getDefaultMessage()));
}
}
15
View Source File : RoleServiceImpl.java
License : Mozilla Public License 2.0
Project Creator : secdec
License : Mozilla Public License 2.0
Project Creator : secdec
@Override
public String validateRole(Role role, BindingResult result) {
if (result.hasFieldErrors("displayName")) {
return FIELD_ERROR;
}
String name = role.getDisplayName();
if (name == null || name.trim().length() == 0) {
result.rejectValue("displayName", null, null, "This field cannot be blank");
return FIELD_ERROR;
}
Role databaseRole = loadRole(name.trim());
if (databaseRole != null && !databaseRole.getId().equals(role.getId())) {
result.rejectValue("displayName", MessageConstants.ERROR_NAMETAKEN);
return FIELD_ERROR;
}
if (name.length() > Role.NAME_LENGTH) {
return FIELD_ERROR;
}
databaseRole = role.getId() == null ? null : loadRole(role.getId());
if (databaseRole != null) {
if (databaseRole.getCanManageUsers() && !role.getCanManageUsers() && !userDao.canRemovePermissionFromRole(role.getId(), "canManageUsers")) {
return "You cannot remove the Manage Users privilege from this role.";
}
if (databaseRole.getCanManageRoles() && !role.getCanManageRoles() && !userDao.canRemovePermissionFromRole(role.getId(), "canManageRoles")) {
return "You cannot remove the Manage Roles privilege from this role.";
}
}
return SUCCESS;
}
15
View Source File : ManageProjectStateController.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
private void validate(@Valid ManageProjectStateForm form, BindingResult result) {
if (result.hasFieldErrors("state")) {
return;
}
if (form.isHandledOffline() && !TRUE.equals(form.getConfirmationOffline())) {
result.rejectValue("confirmationOffline", "validation.field.must.not.be.blank");
return;
}
if (form.isWithdrawn() && !TRUE.equals(form.getConfirmationWithdrawn())) {
result.rejectValue("confirmationWithdrawn", "validation.field.must.not.be.blank");
return;
}
if (form.isCompletedOffline() && !TRUE.equals(form.getConfirmationCompleteOffline())) {
result.rejectValue("confirmationCompleteOffline", "validation.field.must.not.be.blank");
return;
}
if (form.isOnHold()) {
if (isBlank(form.getOnHoldReason())) {
result.rejectValue("onHoldReason", "validation.manage.project.on.hold.reason.required");
}
if (isBlank(form.getOnHoldDetails())) {
result.rejectValue("onHoldDetails", "validation.manage.project.on.hold.details.required");
}
}
}
12
View Source File : IdentitiesEndpoint.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@RequestMapping(method = RequestMethod.POST)
public ResponseEnreplacedy<Idenreplacedy> createIdenreplacedy(@Valid @RequestBody final NewIdenreplacedy newIdenreplacedy, BindingResult bindingResult) throws DuplicateEmailException, InvalidPreplacedwordException {
if (bindingResult.hasFieldErrors("preplacedword")) {
throwExceptionOnInvalidPreplacedword(bindingResult);
}
if (bindingResult.hasFieldErrors("email")) {
throw new DuplicateEmailException();
}
LOG.debug("create request: {}", newIdenreplacedy);
final Idenreplacedy idenreplacedy = createService.createIdenreplacedy(newIdenreplacedy.getEmail(), newIdenreplacedy.getPreplacedword());
LOG.debug("created Idenreplacedy: {}", idenreplacedy);
return ResponseEnreplacedy.created(URI.create("/idenreplacedies/" + idenreplacedy.getUuid())).body(idenreplacedy);
}
10
View Source File : PostController.java
License : GNU Affero General Public License v3.0
Project Creator : ramostear
License : GNU Affero General Public License v3.0
Project Creator : ramostear
@UnaLog(replacedle = "更新文章", type = LogType.UPDATE)
@RequiresRoles(value = { "admin", "editor" }, logical = Logical.OR)
@PostMapping("/{id:\\d+}")
@ResponseBody
public ResponseEnreplacedy<Object> post(@PathVariable("id") Integer id, @Valid @RequestBody PostParam param, BindingResult br) {
if (br.hasFieldErrors()) {
return bad("数据未通过校验");
}
try {
Post post = postService.findById(id);
if (post != null) {
param.updateTo(post);
postService.updateBy(post, param.tags(), param.getCategoryId(), param.getStatus());
return ok();
} else {
return bad();
}
} catch (UnaBootException e) {
return bad();
}
}
10
View Source File : SiteTermsControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void agreeNewTermsAndConditions_notAgreed() throws Exception {
MvcResult result = mockMvc.perform(post("/info/new-terms-and-conditions")).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeHasFieldErrors("form", "agree")).andExpect(model().attributeHasFieldErrorCode("form", "agree", "NotNull")).andExpect(view().name("content/new-terms-and-conditions")).andReturn();
NewSiteTermsAndConditionsForm form = (NewSiteTermsAndConditionsForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("agree"));
replacedertEquals("In order to continue you must agree to the terms and conditions.", bindingResult.getFieldError("agree").getDefaultMessage());
verifyNoMoreInteractions(userRestService);
}
9
View Source File : CompetitionManagementApplicationControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void markAsIneligible_noReason() throws Exception {
long applicationId = 1L;
long compereplacedionId = 2L;
ManagementApplicationViewModel viewModel = mock(ManagementApplicationViewModel.clreplaced);
when(managementApplicationPopulator.populate(eq(applicationId), eq(getLoggedInUser()))).thenReturn(viewModel);
MvcResult result = mockMvc.perform(post("/compereplacedion/{compereplacedionId}/application/{applicationId}", compereplacedionId, applicationId).param("markAsIneligible", "")).andExpect(view().name("compereplacedion-mgt-application-overview")).andReturn();
IneligibleApplicationForm form = (IneligibleApplicationForm) result.getModelAndView().getModel().get("ineligibleForm");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("ineligibleReason"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("ineligibleReason").getDefaultMessage());
}
7
View Source File : ReviewInviteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void noDecisionMade() throws Exception {
ReviewInviteResource inviteResource = newReviewInviteResource().withCompereplacedionName("my compereplacedion").build();
when(reviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
ReviewInviteForm expectedForm = new ReviewInviteForm();
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")).andExpect(status().isOk()).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "acceptInvitation")).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("rejectionReasons", rejectionReasons)).andExpect(model().attributeExists("model")).andExpect(view().name("replacedessor-panel-invite")).andReturn();
ReviewInviteViewModel model = (ReviewInviteViewModel) result.getModelAndView().getModel().get("model");
replacedertEquals("hash", model.getPanelInviteHash());
replacedertEquals("my compereplacedion", model.getCompereplacedionName());
ReviewInviteForm form = (ReviewInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("acceptInvitation"));
replacedertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage());
verify(reviewInviteRestService).openInvite("hash");
verifyNoMoreInteractions(reviewInviteRestService);
}
7
View Source File : YourFundingFormValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void validate() {
String unsavedId = generateUnsavedRowId();
YourFundingPercentageForm form = new YourFundingPercentageForm();
form.setRequestingFunding(true);
form.setGrantClaimPercentage(BigDecimal.valueOf(0));
long compereplacedionId = 1l;
ApplicationResource applicationResource = newApplicationResource().withCompereplacedion(compereplacedionId).build();
CompereplacedionApplicationConfigResource compereplacedionApplicationConfigResource = newCompereplacedionApplicationConfigResource().build();
when(applicationRestService.getApplicationById(anyLong())).thenReturn(restSuccess(applicationResource));
when(compereplacedionApplicationConfigRestService.findOneByCompereplacedionId(compereplacedionId)).thenReturn(restSuccess(compereplacedionApplicationConfigResource));
form.setOtherFunding(true);
OtherFundingRowForm emptyRow = new OtherFundingRowForm(new OtherFunding(null, null, "Valid", "01-2019", new BigDecimal(123), 1L));
OtherFundingRowForm existingRow = new OtherFundingRowForm(new OtherFunding(20L, null, null, "InvalidPattern", new BigDecimal("012345678901234567890"), 1L));
form.setOtherFundingRows(asMap(unsavedId, emptyRow, "20", existingRow));
BindingResult bindingResult = new DataBinder(form).getBindingResult();
UserResource user = newUserResource().build();
long applicationId = 2L;
service.validate(form, bindingResult, user, applicationId);
replacedertFalse(bindingResult.hasFieldErrors("requestingFunding"));
replacedertTrue(bindingResult.hasFieldErrors("grantClaimPercentage"));
replacedertFalse(bindingResult.hasFieldErrors("otherFunding"));
replacedertFalse(bindingResult.hasFieldErrors(String.format("otherFundingRows[%s].source", unsavedId)));
replacedertFalse(bindingResult.hasFieldErrors(String.format("otherFundingRows[%s].date", unsavedId)));
replacedertFalse(bindingResult.hasFieldErrors(String.format("otherFundingRows[%s].fundingAmount", unsavedId)));
replacedertTrue(bindingResult.hasFieldErrors("otherFundingRows[20].source"));
replacedertTrue(bindingResult.hasFieldErrors("otherFundingRows[20].date"));
replacedertTrue(bindingResult.hasFieldErrors("otherFundingRows[20].fundingAmount"));
}
7
View Source File : UserController.java
License : MIT License
Project Creator : hnjaman
License : MIT License
Project Creator : hnjaman
@PostMapping("/preplacedport")
public ResponseEnreplacedy<Object> createPreplacedport(@RequestBody @Valid Preplacedport newpreplacedport, BindingResult bindingResult) {
if (bindingResult.hasFieldErrors()) {
errors = new HashMap<>();
for (FieldError error : bindingResult.getFieldErrors()) {
errors.put(error.getField(), error.getDefaultMessage());
}
return new ResponseEnreplacedy<>(errors, HttpStatus.NOT_ACCEPTABLE);
}
Preplacedport preplacedppid = ipreplacedport.findByPpid(newpreplacedport.getPpid());
Preplacedport preplacednid = ipreplacedport.findByNid(newpreplacedport.getNid());
if (preplacednid != null || preplacedppid != null) {
return new ResponseEnreplacedy<>(HttpStatus.CONFLICT);
}
return new ResponseEnreplacedy<>(ipreplacedport.save(newpreplacedport), HttpStatus.OK);
}
6
View Source File : ScheduledScanController.java
License : Mozilla Public License 2.0
Project Creator : secdec
License : Mozilla Public License 2.0
Project Creator : secdec
@RequestMapping(value = "/addScheduledScan", method = RequestMethod.POST)
@ResponseBody
public RestResponse<List<ScheduledScan>> addScheduledScan(@PathVariable("appId") int appId, @PathVariable("orgId") int orgId, @Valid @ModelAttribute ScheduledScan scheduledScan, BindingResult result) {
if (scheduledScanService == null) {
return RestResponse.failure("This method cannot be reached in the Community Edition.");
}
log.info("Start adding scheduled scan to application " + appId);
if (!PermissionUtils.isAuthorized(Permission.CAN_MANAGE_APPLICATIONS, orgId, appId)) {
return RestResponse.failure("You are not allowed to modify scheduled scans for this application.");
}
Application application = applicationService.loadApplication(appId);
if (application == null || !application.isActive()) {
return RestResponse.failure("Application was not found for ID " + appId);
}
scheduledScanService.validateDate(scheduledScan, result);
if (result.hasErrors()) {
if (result.hasFieldErrors("scanConfig")) {
return RestResponse.failure("Scan Config file is invalid.");
} else
return FormRestResponse.failure("Encountered errors.", result);
}
scheduledScan.setApplication(application);
String errMsg = scheduledScanService.validate(scheduledScan);
if (errMsg != null) {
return RestResponse.failure(errMsg);
}
int scheduledScanId = scheduledScanService.save(appId, scheduledScan);
if (scheduledScanId < 0) {
return RestResponse.failure("Adding Scheduled Scan failed.");
}
// Add new job to scheduler
if (scheduledScanScheduler.addScheduledScan(scheduledScan)) {
log.info("Successfully added new scheduled scan to scheduler");
return RestResponse.success(application.getScheduledScans());
} else {
log.warn("Failed to add new scheduled scan to scheduler");
String message = "Adding new " + scheduledScan.getFrequency() + " Scan for " + scheduledScan.getScanner() + " failed.";
scheduledScanService.delete(scheduledScan);
return RestResponse.failure(message);
}
}
6
View Source File : InterviewInviteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void noDecisionMade() throws Exception {
InterviewInviteResource inviteResource = newInterviewInviteResource().withCompereplacedionName("my compereplacedion").build();
when(interviewInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
InterviewInviteForm expectedForm = new InterviewInviteForm();
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")).andExpect(status().isOk()).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "acceptInvitation")).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("rejectionReasons", rejectionReasons)).andExpect(model().attributeExists("model")).andExpect(view().name("replacedessor-interview-invite")).andReturn();
InterviewInviteViewModel model = (InterviewInviteViewModel) result.getModelAndView().getModel().get("model");
replacedertEquals("hash", model.getPanelInviteHash());
replacedertEquals("my compereplacedion", model.getCompereplacedionName());
InterviewInviteForm form = (InterviewInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("acceptInvitation"));
replacedertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage());
verify(interviewInviteRestService).openInvite("hash");
verifyNoMoreInteractions(interviewInviteRestService);
}
6
View Source File : IndexPicController.java
License : MIT License
Project Creator : cjbi
License : MIT License
Project Creator : cjbi
@ResponseBody
@RequestMapping(value = "/indexPic/add", method = RequestMethod.POST)
public ResponseData add(@Validated IndexPic indexPic, HttpSession session, BindingResult br, MultipartFile image) {
if (br.hasFieldErrors()) {
return ResponseData.FAILED_NO_DATA;
}
// 处理图片流数据
String realPath = session.getServletContext().getRealPath("");
String oldName = image.getOriginalFilename();
String newName = new Date().getTime() + "." + FilenameUtils.getExtension(oldName);
try {
// 对图片流进行压缩,生成文件和缩略图保存到指定文件夹
writeIndexPic(realPath, newName, image.getInputStream());
} catch (IOException e) {
e.printStackTrace();
return new ResponseData(false, e.getMessage());
}
indexPic.setOldName(oldName);
indexPic.setNewName(newName);
indexPicService.add(indexPic);
if (indexPic.getStatus() != 0) {
indexService.generateBody();
}
return ResponseData.SUCCESS_NO_DATA;
}
5
View Source File : PostController.java
License : GNU Affero General Public License v3.0
Project Creator : ramostear
License : GNU Affero General Public License v3.0
Project Creator : ramostear
@UnaLog(replacedle = "新增文章", type = LogType.INSERT)
@RequiresRoles(value = { "admin", "editor" }, logical = Logical.OR)
@ResponseBody
@PostMapping("/create")
public ResponseEnreplacedy<Object> create(@Valid @RequestBody PostParam param, BindingResult br) {
if (br.hasFieldErrors()) {
return bad("数据未通过校验");
}
try {
if (StringUtils.isBlank(param.getAuthor())) {
param.setAuthor(currentUser().getUsername());
}
if (!currentUser().getRole().equals(Authorized.ADMIN.getName())) {
List<Integer> categoryIds = userCategoryService.findAllCategoryByUserId(currentUser().getId());
if (CollectionUtils.isEmpty(categoryIds) || !categoryIds.contains(param.getCategoryId())) {
return bad();
}
}
Post post = param.convertTo();
post.setUserId(currentUser().getId());
postService.createBy(post, param.tags(), param.getCategoryId(), param.getStatus());
return ok();
} catch (UnaBootException e) {
return bad();
}
}
5
View Source File : FinanceChecksQueriesAddQueryTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewQueryNoFieldsSet() throws Exception {
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/new-query?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("queryreplacedle", "").param("query", "").param("section", "")).andExpect(view().name("project/financecheck/new-query")).andReturn();
FinanceChecksQueriesAddQueryForm form = (FinanceChecksQueriesAddQueryForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getQueryreplacedle());
replacedertEquals("", form.getQuery());
replacedertEquals("", form.getSection().toUpperCase());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(3, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("queryreplacedle"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("queryreplacedle").getDefaultMessage());
replacedertTrue(bindingResult.hasFieldErrors("query"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("query").getDefaultMessage());
replacedertTrue(bindingResult.hasFieldErrors("section"));
replacedertEquals("The section is not recognised, please select a valid section.", bindingResult.getFieldError("section").getDefaultMessage());
}
5
View Source File : FinanceChecksNotesAddNoteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewNoteNoFieldsSet() throws Exception {
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/new-note").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("notereplacedle", "").param("note", "").cookie(originCookie)).andExpect(view().name("project/financecheck/new-note")).andReturn();
FinanceChecksNotesAddNoteForm form = (FinanceChecksNotesAddNoteForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getNotereplacedle());
replacedertEquals("", form.getNote());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(2, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("notereplacedle"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("notereplacedle").getDefaultMessage());
replacedertTrue(bindingResult.hasFieldErrors("note"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("note").getDefaultMessage());
}
4
View Source File : FinanceChecksQueriesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseNoFieldsSet() throws Exception {
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/" + queryId + "/new-response?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", "")).andExpect(view().name("project/financecheck/queries")).andReturn();
FinanceChecksQueriesAddResponseForm form = (FinanceChecksQueriesAddResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("response").getDefaultMessage());
}
4
View Source File : FinanceChecksNotesAddNoteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewNoteFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/new-note").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("notereplacedle", tooLong).param("note", tooLong).cookie(originCookie)).andExpect(view().name("project/financecheck/new-note")).andReturn();
FinanceChecksNotesAddNoteForm form = (FinanceChecksNotesAddNoteForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getNotereplacedle());
replacedertEquals(tooLong, form.getNote());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(2, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("notereplacedle"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("notereplacedle").getDefaultMessage());
replacedertTrue(bindingResult.hasFieldErrors("note"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("note").getDefaultMessage());
}
4
View Source File : FinanceChecksNotesAddNoteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewNoteTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/new-note").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("notereplacedle", "replacedle").param("note", tooManyWords).cookie(originCookie)).andExpect(view().name("project/financecheck/new-note")).andReturn();
FinanceChecksNotesAddNoteForm form = (FinanceChecksNotesAddNoteForm) result.getModelAndView().getModel().get("form");
replacedertEquals("replacedle", form.getNotereplacedle());
replacedertEquals(tooManyWords, form.getNote());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("note"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("note").getDefaultMessage());
}
4
View Source File : CompetitionInviteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void noDecisionMade() throws Exception {
CompereplacedionInviteResource inviteResource = newCompereplacedionInviteResource().withCompereplacedionName("my compereplacedion").build();
when(compereplacedionInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
String comment = RandomStringUtils.random(5001);
Boolean accept = false;
CompereplacedionInviteForm expectedForm = new CompereplacedionInviteForm();
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash")).andExpect(status().isOk()).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "acceptInvitation")).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("rejectionReasons", rejectionReasons)).andExpect(model().attributeExists("model")).andExpect(view().name("replacedessor-compereplacedion-invite")).andReturn();
CompereplacedionInviteViewModel model = (CompereplacedionInviteViewModel) result.getModelAndView().getModel().get("model");
replacedertEquals("hash", model.getCompereplacedionInviteHash());
replacedertEquals("my compereplacedion", model.getCompereplacedionName());
CompereplacedionInviteForm form = (CompereplacedionInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("acceptInvitation"));
replacedertEquals("Please indicate your decision.", bindingResult.getFieldError("acceptInvitation").getDefaultMessage());
verify(compereplacedionInviteRestService).openInvite("hash");
verifyNoMoreInteractions(compereplacedionInviteRestService);
}
4
View Source File : AssessmentAssignmentControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void rejectreplacedignment_neitherAcceptOrReject() throws Exception {
Long replacedessmentId = 1L;
long compereplacedionId = 3L;
String comment = String.join(" ", nCopies(100, "comment"));
replacedessmentResource replacedessment = newreplacedessmentResource().with(id(replacedessmentId)).withApplication(APPLICATION_ID).withApplicationName("Application name").withActivityState(PENDING).withCompereplacedion(compereplacedionId).build();
when(replacedessmentService.getreplacedignableById(replacedessmentId)).thenReturn(replacedessment);
// The non-js confirmation view should be returned with the comment pre-populated in the form and an error for the missing reason
replacedessmentreplacedignmentForm expectedForm = new replacedessmentreplacedignmentForm();
replacedessmentreplacedignmentViewModel expectedViewModel = new replacedessmentreplacedignmentViewModel(replacedessmentId, compereplacedionId, "Application name", partners, leadOrganisation, "Project summary");
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/replacedignment/respond", replacedessmentId).contentType(MediaType.APPLICATION_FORM_URLENCODED).param("replacedessmentAccept", "")).andExpect(status().isOk()).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("model", expectedViewModel)).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "replacedessmentAccept")).andExpect(view().name("replacedessment/replacedessment-invitation")).andReturn();
replacedessmentreplacedignmentForm form = (replacedessmentreplacedignmentForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("replacedessmentAccept"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("replacedessmentAccept").getDefaultMessage());
InOrder inOrder = inOrder(replacedessmentService, formInputResponseRestService, processRoleRestService, organisationService);
inOrder.verify(replacedessmentService).getreplacedignableById(replacedessmentId);
inOrder.verify(formInputResponseRestService).getByApplicationIdAndQuestionSetupType(APPLICATION_ID, PROJECT_SUMMARY);
inOrder.verify(processRoleRestService).findProcessRole(APPLICATION_ID);
inOrder.verify(organisationService).getApplicationOrganisations(processRoleResources);
inOrder.verify(organisationService).getApplicationLeadOrganisation(processRoleResources);
inOrder.verifyNoMoreInteractions();
}
3
View Source File : SystemSettingsController.java
License : Mozilla Public License 2.0
Project Creator : secdec
License : Mozilla Public License 2.0
Project Creator : secdec
@JsonView(AllViews.FormInfo.clreplaced)
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Object processSubmit(@ModelAttribute DefaultConfiguration defaultConfiguration, HttpServletRequest request, BindingResult bindingResult) {
if (defaultConfiguration.getDeleteUploadedFiles()) {
try {
scanService.deleteScanFileLocations();
defaultConfiguration.setDeleteUploadedFiles(false);
} catch (RestIOException e) {
return RestResponse.failure("Unable to delete files in 'File Upload Location' directory." + e.getMessage());
}
}
if (defaultConfiguration.getSessionTimeout() != null && defaultConfiguration.getSessionTimeout() > 30) {
bindingResult.reject("sessionTimeout", null, "30 is the maximum.");
}
if (defaultConfiguration.fileUploadLocationExists()) {
checkingFolder(defaultConfiguration, bindingResult);
}
// This was added because Spring autobinding was not saving the export fields properly
List<CSVExportField> exportFields = list();
Map<String, String[]> params = request.getParameterMap();
int index = 0;
while (index != -1) {
String key = "csvExportFields[" + index + "]";
String[] enumValue = params.get(key);
if (enumValue != null) {
exportFields.add(CSVExportField.valueOf(enumValue[0]));
index++;
} else {
index = -1;
}
}
defaultConfiguration.setCsvExportFields(exportFields);
Map<String, String> errors = addReportErrors(defaultConfiguration);
if (bindingResult.hasErrors() || errors.size() > 0) {
// TODO look into this
if (bindingResult.hasFieldErrors("proxyPort")) {
bindingResult.reject("proxyPort", new Object[] {}, "Please enter a valid port number.");
}
return FormRestResponse.failure("Unable save System Settings. Try again.", bindingResult, errors);
} else {
defaultConfigService.saveConfiguration(defaultConfiguration);
return success(defaultConfiguration);
}
}
3
View Source File : FinanceChecksQueriesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/" + queryId + "/new-response?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooLong)).andExpect(view().name("project/financecheck/queries")).andReturn();
FinanceChecksQueriesAddResponseForm form = (FinanceChecksQueriesAddResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("response").getDefaultMessage());
}
3
View Source File : FinanceChecksQueriesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/" + queryId + "/new-response?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooManyWords)).andExpect(view().name("project/financecheck/queries")).andReturn();
FinanceChecksQueriesAddResponseForm form = (FinanceChecksQueriesAddResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooManyWords, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("response").getDefaultMessage());
}
3
View Source File : FinanceChecksQueriesAddQueryTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewQueryTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/new-query?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("queryreplacedle", "replacedle").param("query", tooManyWords).param("section", FinanceChecksSectionType.VIABILITY.name())).andExpect(view().name("project/financecheck/new-query")).andReturn();
FinanceChecksQueriesAddQueryForm form = (FinanceChecksQueriesAddQueryForm) result.getModelAndView().getModel().get("form");
replacedertEquals("replacedle", form.getQueryreplacedle());
replacedertEquals(tooManyWords, form.getQuery());
replacedertEquals(FinanceChecksSectionType.VIABILITY.name(), form.getSection().toUpperCase());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("query"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("query").getDefaultMessage());
}
3
View Source File : FinanceChecksQueriesAddQueryTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewQueryFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/new-query?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("queryreplacedle", tooLong).param("query", tooLong).param("section", FinanceChecksSectionType.VIABILITY.name())).andExpect(view().name("project/financecheck/new-query")).andReturn();
FinanceChecksQueriesAddQueryForm form = (FinanceChecksQueriesAddQueryForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getQueryreplacedle());
replacedertEquals(tooLong, form.getQuery());
replacedertEquals(FinanceChecksSectionType.VIABILITY.name(), form.getSection().toUpperCase());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(2, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("queryreplacedle"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("queryreplacedle").getDefaultMessage());
replacedertTrue(bindingResult.hasFieldErrors("query"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("query").getDefaultMessage());
}
3
View Source File : AssessorRegistrationControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void submitYourDetails_Incomplete() throws Exception {
replacedle replacedle = replacedle.Mr;
String phoneNumber = "12345678";
String preplacedword = "P@ssword1234";
String inviteHash = "hash";
CompereplacedionInviteResource compereplacedionInviteResource = newCompereplacedionInviteResource().withEmail("[email protected]").build();
when(compereplacedionInviteRestService.getInvite(inviteHash)).thenReturn(RestResult.restSuccess(compereplacedionInviteResource));
MvcResult result = mockMvc.perform(post("/registration/{inviteHash}/register", inviteHash).contentType(APPLICATION_FORM_URLENCODED).param("replacedle", replacedle.name()).param("phoneNumber", phoneNumber).param("preplacedword", preplacedword)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "firstName")).andExpect(model().attributeHasFieldErrors("form", "lastName")).andExpect(view().name("registration/register")).andReturn();
RegistrationForm form = (RegistrationForm) result.getModelAndView().getModel().get("form");
replacedertEquals(phoneNumber, form.getPhoneNumber());
replacedertEquals(preplacedword, form.getPreplacedword());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(3, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("firstName"));
replacedertTrue(bindingResult.hasFieldErrors("lastName"));
replacedertTrue(bindingResult.hasFieldErrors("addressForm.postcodeInput"));
replacedertEquals("Please enter a first name.", bindingResult.getFieldError("firstName").getDefaultMessage());
replacedertEquals("Please enter a last name.", bindingResult.getFieldError("lastName").getDefaultMessage());
replacedertEquals("validation.standard.postcodesearch.required", bindingResult.getFieldError("addressForm.postcodeInput").getCode());
}
3
View Source File : AssessorRegistrationControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void submitYourDetails_InvalidNames() throws Exception {
replacedle replacedle = replacedle.Mr;
String phoneNumber = "12345678";
String preplacedword = "P@ssword1234";
String firstName = "abc^%$921";
String lastName = "xyz*(&123";
String inviteHash = "hash";
CompereplacedionInviteResource compereplacedionInviteResource = newCompereplacedionInviteResource().withEmail("[email protected]").build();
when(compereplacedionInviteRestService.getInvite(inviteHash)).thenReturn(RestResult.restSuccess(compereplacedionInviteResource));
MvcResult result = mockMvc.perform(post("/registration/{inviteHash}/register", inviteHash).contentType(APPLICATION_FORM_URLENCODED).param("replacedle", replacedle.name()).param("phoneNumber", phoneNumber).param("preplacedword", preplacedword).param("firstName", firstName).param("lastName", lastName)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "firstName")).andExpect(model().attributeHasFieldErrors("form", "lastName")).andExpect(view().name("registration/register")).andReturn();
RegistrationForm form = (RegistrationForm) result.getModelAndView().getModel().get("form");
replacedertEquals(phoneNumber, form.getPhoneNumber());
replacedertEquals(preplacedword, form.getPreplacedword());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(3, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("firstName"));
replacedertTrue(bindingResult.hasFieldErrors("lastName"));
replacedertTrue(bindingResult.hasFieldErrors("addressForm.postcodeInput"));
replacedertEquals("Invalid first name.", bindingResult.getFieldError("firstName").getDefaultMessage());
replacedertEquals("Invalid last name.", bindingResult.getFieldError("lastName").getDefaultMessage());
replacedertEquals("validation.standard.postcodesearch.required", bindingResult.getFieldError("addressForm.postcodeInput").getCode());
}
3
View Source File : AssessorProfileSkillsEditControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void submitSkills_exceedsWordLimit() throws Exception {
BusinessType businessType = BUSINESS;
String skillAreas = String.join(" ", nCopies(101, "skill"));
List<InnovationAreaResource> innovationAreaResources = setUpInnovationAreasForSector("Emerging and enabling", "Data", "Cyber Security");
UserResource userResource = setUpProfileSkills(ACADEMIC, "skill1 skill2 skill3", innovationAreaResources);
Map<String, List<String>> expectedInnovationAreas = new LinkedHashMap<>();
expectedInnovationAreas.put("Emerging and enabling", asList("Data", "Cyber Security"));
replacedessorProfileEditSkillsViewModel expectedModel = new replacedessorProfileEditSkillsViewModel(expectedInnovationAreas);
MvcResult result = mockMvc.perform(post("/profile/skills/edit").contentType(APPLICATION_FORM_URLENCODED).param("replacedessorType", businessType.name()).param("skillAreas", skillAreas)).andExpect(status().isOk()).andExpect(model().attribute("model", expectedModel)).andExpect(model().attributeExists("form")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "skillAreas")).andExpect(view().name("profile/skills-edit")).andReturn();
replacedessorProfileSkillsForm form = (replacedessorProfileSkillsForm) result.getModelAndView().getModel().get("form");
replacedertEquals(businessType, form.getreplacedessorType());
replacedertEquals(skillAreas, form.getSkillAreas());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("skillAreas"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("skillAreas").getDefaultMessage());
replacedertEquals(100, bindingResult.getFieldError("skillAreas").getArguments()[1]);
verify(profileRestService, only()).getProfileSkills(userResource.getId());
}
3
View Source File : AssessorProfileSkillsEditControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void submitSkills_incomplete() throws Exception {
String skillAreas = String.join(" ", nCopies(100, "skill"));
List<InnovationAreaResource> innovationAreaResources = setUpInnovationAreasForSector("Emerging and enabling", "Data", "Cyber Security");
UserResource userResource = setUpProfileSkills(ACADEMIC, "skill1 skill2 skill3", innovationAreaResources);
Map<String, List<String>> expectedInnovationAreas = new LinkedHashMap<>();
expectedInnovationAreas.put("Emerging and enabling", asList("Data", "Cyber Security"));
replacedessorProfileEditSkillsViewModel expectedModel = new replacedessorProfileEditSkillsViewModel(expectedInnovationAreas);
MvcResult result = mockMvc.perform(post("/profile/skills/edit").contentType(APPLICATION_FORM_URLENCODED).param("skillAreas", skillAreas)).andExpect(status().isOk()).andExpect(model().attribute("model", expectedModel)).andExpect(model().attributeExists("form")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "replacedessorType")).andExpect(view().name("profile/skills-edit")).andReturn();
replacedessorProfileSkillsForm form = (replacedessorProfileSkillsForm) result.getModelAndView().getModel().get("form");
replacedertNull(form.getreplacedessorType());
replacedertEquals(skillAreas, form.getSkillAreas());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("replacedessorType"));
replacedertEquals("Please select an replacedessor type.", bindingResult.getFieldError("replacedessorType").getDefaultMessage());
verify(profileRestService, only()).getProfileSkills(userResource.getId());
}
2
View Source File : FinanceChecksNotesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewCommentNoFieldsSet() throws Exception {
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.loadNotes(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(notes));
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/" + noteId + "/new-comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("comment", "").cookie(originCookie)).andExpect(view().name("project/financecheck/notes")).andReturn();
FinanceChecksNotesAddCommentForm form = (FinanceChecksNotesAddCommentForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getComment());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("comment"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("comment").getDefaultMessage());
}
2
View Source File : CompetitionManagementApplicationControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void reinstateIneligibleApplication_failureUpdatingState() throws Exception {
long compereplacedionId = 1L;
ApplicationResource applicationResource = newApplicationResource().withCompereplacedion(compereplacedionId).withName("Plastic reprocessing with zero waste").build();
ReinstateIneligibleApplicationViewModel expectedViewModel = new ReinstateIneligibleApplicationViewModel(compereplacedionId, applicationResource.getId(), "Plastic reprocessing with zero waste");
when(applicationRestService.updateApplicationState(applicationResource.getId(), SUBMITTED)).thenReturn(restFailure(internalServerErrorError()));
when(applicationRestService.getApplicationById(applicationResource.getId())).thenReturn(restSuccess(applicationResource));
when(reinstateIneligibleApplicationModelPopulator.populateModel(applicationResource)).thenReturn(expectedViewModel);
MvcResult mvcResult = mockMvc.perform(post("/compereplacedion/{compereplacedionId}/application/{applicationId}/reinstateIneligibleApplication", compereplacedionId, applicationResource.getId())).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attribute("model", expectedViewModel)).andExpect(model().hasErrors()).andExpect(model().errorCount(1)).andExpect(view().name("application/reinstate-ineligible-application-confirm")).andReturn();
ReinstateIneligibleApplicationForm form = (ReinstateIneligibleApplicationForm) mvcResult.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertEquals(1, bindingResult.getGlobalErrorCount());
replacedertFalse(bindingResult.hasFieldErrors());
replacedertEquals(CommonFailureKeys.GENERAL_UNEXPECTED_ERROR.getErrorKey(), bindingResult.getGlobalError().getCode());
InOrder inOrder = inOrder(applicationRestService);
inOrder.verify(applicationRestService).updateApplicationState(applicationResource.getId(), SUBMITTED);
inOrder.verify(applicationRestService).getApplicationById(applicationResource.getId());
inOrder.verifyNoMoreInteractions();
}
2
View Source File : AssessmentSummaryControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void save_exceedsWordLimit() throws Exception {
CompereplacedionResource compereplacedionResource = setupCompereplacedionResource();
replacedessmentResource replacedessmentResource = setupreplacedessment(1L, compereplacedionResource.getId());
List<QuestionResource> questionResources = setupQuestions(compereplacedionResource.getId(), replacedessmentResource.getId());
String feedback = String.join(" ", nCopies(101, "feedback"));
String comment = String.join(" ", nCopies(101, "comment"));
when(replacedessorFormInputResponseRestService.getreplacedessmentDetails(replacedessmentResource.getId())).thenReturn(restSuccess(new replacedessmentDetailsResource(questionResources, replacedessmentFormInputs, replacedessorResponses)));
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/summary", replacedessmentResource.getId()).contentType(APPLICATION_FORM_URLENCODED).param("fundingConfirmation", "true").param("feedback", feedback).param("comment", comment)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "feedback")).andExpect(model().attributeHasFieldErrors("form", "comment")).andExpect(view().name("replacedessment/application-summary")).andReturn();
replacedessmentSummaryForm form = (replacedessmentSummaryForm) result.getModelAndView().getModel().get("form");
replacedertTrue(form.getFundingConfirmation());
replacedertEquals(feedback, form.getFeedback());
replacedertEquals(comment, form.getComment());
BindingResult bindingResult = form.getBindingResult();
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(2, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("feedback"));
replacedertTrue(bindingResult.hasFieldErrors("comment"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("feedback").getDefaultMessage());
replacedertEquals(100, bindingResult.getFieldError("feedback").getArguments()[1]);
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("comment").getDefaultMessage());
replacedertEquals(100, bindingResult.getFieldError("comment").getArguments()[1]);
verify(replacedessmentService).getById(replacedessmentResource.getId());
verifyNoMoreInteractions(replacedessmentService);
}
2
View Source File : AssessorProfileSkillsEditControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void submitSkills_exceedsCharacterSizeLimit() throws Exception {
BusinessType businessType = BUSINESS;
String skillAreas = RandomStringUtils.random(5001);
List<InnovationAreaResource> innovationAreaResources = setUpInnovationAreasForSector("Emerging and enabling", "Data", "Cyber Security");
UserResource userResource = setUpProfileSkills(ACADEMIC, "skill1 skill2 skill3", innovationAreaResources);
Map<String, List<String>> expectedInnovationAreas = new LinkedHashMap<>();
expectedInnovationAreas.put("Emerging and enabling", asList("Data", "Cyber Security"));
replacedessorProfileEditSkillsViewModel expectedModel = new replacedessorProfileEditSkillsViewModel(expectedInnovationAreas);
MvcResult result = mockMvc.perform(post("/profile/skills/edit").contentType(APPLICATION_FORM_URLENCODED).param("replacedessorType", businessType.name()).param("skillAreas", skillAreas)).andExpect(status().isOk()).andExpect(model().attribute("model", expectedModel)).andExpect(model().attributeExists("form")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "skillAreas")).andExpect(view().name("profile/skills-edit")).andReturn();
replacedessorProfileSkillsForm form = (replacedessorProfileSkillsForm) result.getModelAndView().getModel().get("form");
replacedertEquals(businessType, form.getreplacedessorType());
replacedertEquals(skillAreas, form.getSkillAreas());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("skillAreas"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("skillAreas").getDefaultMessage());
replacedertEquals(5000, bindingResult.getFieldError("skillAreas").getArguments()[1]);
verify(profileRestService, only()).getProfileSkills(userResource.getId());
}
2
View Source File : CompetitionInviteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void rejectInvite_exceedsWordLimit() throws Exception {
CompereplacedionInviteResource inviteResource = newCompereplacedionInviteResource().withCompereplacedionName("my compereplacedion").build();
when(compereplacedionInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
String comment = String.join(" ", nCopies(101, "comment"));
Boolean accept = false;
CompereplacedionInviteForm expectedForm = new CompereplacedionInviteForm();
expectedForm.setAcceptInvitation(accept);
expectedForm.setRejectReason(newRejectionReasonResource().with(id(1L)).build());
expectedForm.setRejectComment(comment);
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("acceptInvitation", accept.toString()).param("rejectReason", "1").param("rejectComment", comment)).andExpect(status().isOk()).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "rejectComment")).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("rejectionReasons", rejectionReasons)).andExpect(model().attributeExists("model")).andExpect(view().name("replacedessor-compereplacedion-invite")).andReturn();
CompereplacedionInviteViewModel model = (CompereplacedionInviteViewModel) result.getModelAndView().getModel().get("model");
replacedertEquals("hash", model.getCompereplacedionInviteHash());
replacedertEquals("my compereplacedion", model.getCompereplacedionName());
CompereplacedionInviteForm form = (CompereplacedionInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("rejectComment"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("rejectComment").getDefaultMessage());
replacedertEquals(100, bindingResult.getFieldError("rejectComment").getArguments()[1]);
verify(compereplacedionInviteRestService).openInvite("hash");
verifyNoMoreInteractions(compereplacedionInviteRestService);
}
2
View Source File : AssessmentAssignmentControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void rejectreplacedignment_noReason() throws Exception {
Long replacedessmentId = 1L;
long compereplacedionId = 3L;
Boolean accept = false;
String comment = String.join(" ", nCopies(100, "comment"));
replacedessmentResource replacedessment = newreplacedessmentResource().with(id(replacedessmentId)).withApplication(APPLICATION_ID).withApplicationName("Application name").withActivityState(PENDING).withCompereplacedion(compereplacedionId).build();
when(replacedessmentService.getreplacedignableById(replacedessmentId)).thenReturn(replacedessment);
// The non-js confirmation view should be returned with the comment pre-populated in the form and an error for the missing reason
replacedessmentreplacedignmentForm expectedForm = new replacedessmentreplacedignmentForm();
expectedForm.setreplacedessmentAccept(accept);
expectedForm.setRejectComment(comment);
replacedessmentreplacedignmentViewModel expectedViewModel = new replacedessmentreplacedignmentViewModel(replacedessmentId, compereplacedionId, "Application name", partners, leadOrganisation, "Project summary");
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/replacedignment/respond", replacedessmentId).contentType(MediaType.APPLICATION_FORM_URLENCODED).param("replacedessmentAccept", accept.toString()).param("rejectReason", "").param("rejectComment", comment)).andExpect(status().isOk()).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("model", expectedViewModel)).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "rejectReasonValid")).andExpect(view().name("replacedessment/replacedessment-invitation")).andReturn();
replacedessmentreplacedignmentForm form = (replacedessmentreplacedignmentForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("rejectReasonValid"));
replacedertEquals("Please enter a reason.", bindingResult.getFieldError("rejectReasonValid").getDefaultMessage());
InOrder inOrder = inOrder(replacedessmentService, formInputResponseRestService, processRoleRestService, organisationService);
inOrder.verify(replacedessmentService).getreplacedignableById(replacedessmentId);
inOrder.verify(formInputResponseRestService).getByApplicationIdAndQuestionSetupType(APPLICATION_ID, PROJECT_SUMMARY);
inOrder.verify(processRoleRestService).findProcessRole(APPLICATION_ID);
inOrder.verify(organisationService).getApplicationOrganisations(processRoleResources);
inOrder.verify(organisationService).getApplicationLeadOrganisation(processRoleResources);
inOrder.verifyNoMoreInteractions();
}
1
View Source File : FinanceChecksNotesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewCommentTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.loadNotes(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(notes));
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/" + noteId + "/new-comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("comment", tooManyWords).cookie((originCookie))).andExpect(view().name("project/financecheck/notes")).andReturn();
FinanceChecksNotesAddCommentForm form = (FinanceChecksNotesAddCommentForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooManyWords, form.getComment());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("comment"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("comment").getDefaultMessage());
}
1
View Source File : FinanceChecksNotesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewCommentFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.loadNotes(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(notes));
Cookie originCookie = createOriginCookie();
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/note/" + noteId + "/new-comment").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("comment", tooLong).cookie(originCookie)).andExpect(view().name("project/financecheck/notes")).andReturn();
FinanceChecksNotesAddCommentForm form = (FinanceChecksNotesAddCommentForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getComment());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("comment"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("comment").getDefaultMessage());
}
1
View Source File : AssessmentSummaryControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void save_noFundingConfirmation() throws Exception {
CompereplacedionResource compereplacedionResource = setupCompereplacedionResource();
replacedessmentResource replacedessmentResource = setupreplacedessment(1L, compereplacedionResource.getId());
List<QuestionResource> questionResources = setupQuestions(compereplacedionResource.getId(), replacedessmentResource.getId());
when(replacedessorFormInputResponseRestService.getreplacedessmentDetails(replacedessmentResource.getId())).thenReturn(restSuccess(new replacedessmentDetailsResource(questionResources, replacedessmentFormInputs, replacedessorResponses)));
String feedback = String.join(" ", nCopies(100, "feedback"));
String comment = String.join(" ", nCopies(100, "comment"));
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/summary", replacedessmentResource.getId()).contentType(APPLICATION_FORM_URLENCODED).param("feedback", feedback).param("comment", comment)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "fundingConfirmation")).andExpect(view().name("replacedessment/application-summary")).andReturn();
replacedessmentSummaryForm form = (replacedessmentSummaryForm) result.getModelAndView().getModel().get("form");
replacedertNull(form.getFundingConfirmation());
replacedertEquals(feedback, form.getFeedback());
replacedertEquals(comment, form.getComment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("fundingConfirmation"));
replacedertEquals("You must select an option.", bindingResult.getFieldError("fundingConfirmation").getDefaultMessage());
verify(replacedessmentService).getById(replacedessmentResource.getId());
verifyNoMoreInteractions(replacedessmentService);
}
1
View Source File : AssessmentSummaryControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void save_noFeedbackAndFundingConfirmationIsFalse() throws Exception {
CompereplacedionResource compereplacedionResource = setupCompereplacedionResource();
replacedessmentResource replacedessmentResource = setupreplacedessment(1L, compereplacedionResource.getId());
List<QuestionResource> questionResources = setupQuestions(compereplacedionResource.getId(), replacedessmentResource.getId());
when(replacedessorFormInputResponseRestService.getreplacedessmentDetails(replacedessmentResource.getId())).thenReturn(restSuccess(new replacedessmentDetailsResource(questionResources, replacedessmentFormInputs, replacedessorResponses)));
String comment = String.join(" ", nCopies(100, "comment"));
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/summary", replacedessmentResource.getId()).contentType(APPLICATION_FORM_URLENCODED).param("fundingConfirmation", "false").param("comment", comment)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form")).andExpect(view().name("replacedessment/application-summary")).andReturn();
replacedessmentSummaryForm form = (replacedessmentSummaryForm) result.getModelAndView().getModel().get("form");
replacedertFalse(form.getFundingConfirmation());
replacedertNull(form.getFeedback());
replacedertEquals(comment, form.getComment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("feedback"));
replacedertEquals("Please enter your feedback.", bindingResult.getFieldError("feedback").getDefaultMessage());
verify(replacedessmentService).getById(replacedessmentResource.getId());
verifyNoMoreInteractions(replacedessmentService);
}
1
View Source File : CompetitionInviteControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void rejectInvite_exceedsCharacterSizeLimit() throws Exception {
CompereplacedionInviteResource inviteResource = newCompereplacedionInviteResource().withCompereplacedionName("my compereplacedion").build();
when(compereplacedionInviteRestService.openInvite("hash")).thenReturn(restSuccess(inviteResource));
String comment = RandomStringUtils.random(5001);
Boolean accept = false;
CompereplacedionInviteForm expectedForm = new CompereplacedionInviteForm();
expectedForm.setAcceptInvitation(accept);
expectedForm.setRejectReason(newRejectionReasonResource().with(id(1L)).build());
expectedForm.setRejectComment(comment);
MvcResult result = mockMvc.perform(post(restUrl + "{inviteHash}/decision", "hash").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("acceptInvitation", accept.toString()).param("rejectReason", "1").param("rejectComment", comment)).andExpect(status().isOk()).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "rejectComment")).andExpect(model().attribute("form", expectedForm)).andExpect(model().attribute("rejectionReasons", rejectionReasons)).andExpect(model().attributeExists("model")).andExpect(view().name("replacedessor-compereplacedion-invite")).andReturn();
CompereplacedionInviteViewModel model = (CompereplacedionInviteViewModel) result.getModelAndView().getModel().get("model");
replacedertEquals("hash", model.getCompereplacedionInviteHash());
replacedertEquals("my compereplacedion", model.getCompereplacedionName());
CompereplacedionInviteForm form = (CompereplacedionInviteForm) result.getModelAndView().getModel().get("form");
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("rejectComment"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("rejectComment").getDefaultMessage());
replacedertEquals(5000, bindingResult.getFieldError("rejectComment").getArguments()[1]);
verify(compereplacedionInviteRestService).openInvite("hash");
verifyNoMoreInteractions(compereplacedionInviteRestService);
}
1
View Source File : YourFundingFormValidatorTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void validateYourFundingAmountForm() {
long compereplacedionId = 1l;
ApplicationResource applicationResource = newApplicationResource().withCompereplacedion(compereplacedionId).build();
CompereplacedionApplicationConfigResource compereplacedionApplicationConfigResource = newCompereplacedionApplicationConfigResource().build();
YourFundingAmountForm form = new YourFundingAmountForm();
form.setAmount(new BigDecimal("100"));
form.setOtherFunding(false);
BindingResult bindingResult = new DataBinder(form).getBindingResult();
UserResource user = newUserResource().build();
long applicationId = 2L;
OrganisationResource organisation = OrganisationResourceBuilder.newOrganisationResource().build();
ApplicationFinanceResource baseFinanceResource = mock(ApplicationFinanceResource.clreplaced);
when(organisationRestService.getByUserAndApplicationId(user.getId(), applicationId)).thenReturn(restSuccess(organisation));
when(applicationFinanceRestService.getFinanceDetails(applicationId, organisation.getId())).thenReturn(restSuccess(baseFinanceResource));
when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(applicationResource));
when(compereplacedionApplicationConfigRestService.findOneByCompereplacedionId(compereplacedionId)).thenReturn(restSuccess(compereplacedionApplicationConfigResource));
when(baseFinanceResource.getTotal()).thenReturn(new BigDecimal("99.9"));
service.validate(form, bindingResult, user, applicationId);
replacedertFalse(bindingResult.hasErrors());
when(baseFinanceResource.getTotal()).thenReturn(new BigDecimal("50"));
service.validate(form, bindingResult, user, applicationId);
replacedertTrue(bindingResult.hasErrors());
replacedertTrue(bindingResult.hasFieldErrors("amount"));
}
0
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseNoFieldsSet() throws Exception {
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", "")).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("response").getDefaultMessage());
}
0
View Source File : AssessmentSummaryControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void save_exceedsCharacterSizeLimit() throws Exception {
CompereplacedionResource compereplacedionResource = setupCompereplacedionResource();
replacedessmentResource replacedessmentResource = setupreplacedessment(1L, compereplacedionResource.getId());
List<QuestionResource> questionResources = setupQuestions(compereplacedionResource.getId(), replacedessmentResource.getId());
when(replacedessorFormInputResponseRestService.getreplacedessmentDetails(replacedessmentResource.getId())).thenReturn(restSuccess(new replacedessmentDetailsResource(questionResources, replacedessmentFormInputs, replacedessorResponses)));
String feedback = RandomStringUtils.random(5001);
String comment = RandomStringUtils.random(5001);
MvcResult result = mockMvc.perform(post("/{replacedessmentId}/summary", replacedessmentResource.getId()).contentType(APPLICATION_FORM_URLENCODED).param("fundingConfirmation", "true").param("feedback", feedback).param("comment", comment)).andExpect(status().isOk()).andExpect(model().attributeExists("form")).andExpect(model().attributeExists("model")).andExpect(model().hasErrors()).andExpect(model().attributeHasFieldErrors("form", "feedback")).andExpect(model().attributeHasFieldErrors("form", "comment")).andExpect(view().name("replacedessment/application-summary")).andReturn();
replacedessmentSummaryForm form = (replacedessmentSummaryForm) result.getModelAndView().getModel().get("form");
replacedertTrue(form.getFundingConfirmation());
replacedertEquals(feedback, form.getFeedback());
replacedertEquals(comment, form.getComment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(2, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("feedback"));
replacedertTrue(bindingResult.hasFieldErrors("comment"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("feedback").getDefaultMessage());
replacedertEquals(5000, bindingResult.getFieldError("feedback").getArguments()[1]);
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("comment").getDefaultMessage());
replacedertEquals(5000, bindingResult.getFieldError("comment").getArguments()[1]);
verify(replacedessmentService).getById(replacedessmentResource.getId());
verifyNoMoreInteractions(replacedessmentService);
}
0
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooManyWords)).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooManyWords, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("response").getDefaultMessage());
}
0
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooLong)).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("response").getDefaultMessage());
}
See More Examples