method2testcases
stringlengths
118
3.08k
### Question: CsrfTokenService { CsrfToken generateToken() { return new DefaultCsrfToken(CSRF_HEADER_NAME, CSRF_PARAMETER_NAME, encryptToken()); } @Value("${ifs.web.security.csrf.encryption.password}") void setEncryptionPassword(final String encryptionPassword); @Value("${ifs.web.security.csrf.encryption.salt}") void setEncryptionSalt(final String encryptionSalt); @Value("${ifs.web.security.csrf.token.validity.mins}") void setTokenValidityMins(final int tokenValidityMins); }### Answer: @Test public void test_generateToken() throws Exception { final CsrfToken token = tokenUtility.generateToken(); assertEquals("X-CSRF-TOKEN", token.getHeaderName()); assertEquals("_csrf", token.getParameterName()); final String decrypted = encryptor.decrypt(token.getToken()); final CsrfUidToken parsed = CsrfUidToken.parse(decrypted); assertEquals(UID, parsed.getuId()); } @Test public void test_generateToken_anonymous() throws Exception { SecurityContextHolder.getContext().setAuthentication(null); final CsrfToken token = tokenUtility.generateToken(); final String decrypted = encryptor.decrypt(token.getToken()); final CsrfUidToken parsed = CsrfUidToken.parse(decrypted); assertEquals("ANONYMOUS", parsed.getuId()); }
### Question: CsrfStatelessFilter extends OncePerRequestFilter { @Override protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException { if (!isResourceRequest(request)) { final CsrfToken token = tokenService.generateToken(); request.setAttribute(CsrfToken.class.getName(), token); setTokenAsCookie(response, token); } if (!requireCsrfProtectionMatcher.matches(request)) { filterChain.doFilter(request, response); return; } try { tokenService.validateToken(request); } catch (final CsrfException e) { LOG.warn("Handling access denied for exception", e); accessDeniedHandler.handle(request, response, e); return; } filterChain.doFilter(request, response); } @Value("${ifsEnableDevTools:false}") void setEnableDevTools(boolean enableDevTools); }### Answer: @Test public void test_doFilterInternal_invalid() throws Exception { final MockHttpServletRequest invalidRequest = new MockHttpServletRequest(); invalidRequest.setMethod(POST.toString()); final CsrfException expectedException = new CsrfException("Not allowed"); doThrow(expectedException).when(tokenUtility).validateToken(same(invalidRequest)); filter.doFilterInternal(invalidRequest, response, filterChain); verify(accessDeniedHandler, times(1)).handle(invalidRequest, response, expectedException); verifyZeroInteractions(filterChain); }
### Question: LoggedInUserMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public boolean supportsParameter(MethodParameter parameter) { if(parameter.hasParameterAnnotation(ModelAttribute.class)) { return false; } Class<?> paramType = parameter.getParameterType(); return UserResource.class.isAssignableFrom(paramType); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory); }### Answer: @Test public void supportsParameter_shouldSupportUserResource() { MethodParameter userResourceParameter = new MethodParameter(testMethod, 0); assertTrue(loggedInUserMethodArgumentResolver.supportsParameter(userResourceParameter)); } @Test public void supportsParameter_shouldNotSupportAnotherType() { MethodParameter notAUserResourceParameter = new MethodParameter(testMethod, 1); assertFalse(loggedInUserMethodArgumentResolver.supportsParameter(notAUserResourceParameter)); } @Test public void supportsParameter_shouldNotSupportModelAttributedUserResource() { MethodParameter modelAttributeResourceParameter = new MethodParameter(testMethod, 2); assertFalse(loggedInUserMethodArgumentResolver.supportsParameter(modelAttributeResourceParameter)); }
### Question: LoggedInUserMethodArgumentResolver implements HandlerMethodArgumentResolver { @Override public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception { HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class); return userAuthenticationService.getAuthenticatedUser(request); } @Override boolean supportsParameter(MethodParameter parameter); @Override Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory); }### Answer: @Test public void resolveArgument_shouldReturnUserResource() throws Exception { MockHttpServletRequest mockRequest = new MockHttpServletRequest(); mockRequest.addParameter("uid", "123"); NativeWebRequest webRequest = new ServletWebRequest(mockRequest); MethodParameter userResourceParameter = new MethodParameter(testMethod, 0); UserResource userResource = newUserResource().withFirstName("Steve").build(); when(userAuthenticationService.getAuthenticatedUser(isA(HttpServletRequest.class))).thenReturn(userResource); UserResource loggedInUser = (UserResource) loggedInUserMethodArgumentResolver.resolveArgument(userResourceParameter, modelAndViewContainer, webRequest, webDataBinderFactory); verify(userAuthenticationService, times(1)).getAuthenticatedUser(isA(HttpServletRequest.class)); verifyNoMoreInteractions(userAuthenticationService); assertEquals("Steve", loggedInUser.getFirstName()); }
### Question: ThreadsafeModel implements Model { @Override public boolean containsAttribute(String attributeName) { return withReadLock(() -> model.containsAttribute(attributeName)); } ThreadsafeModel(Model model); @Override Model addAttribute(String attributeName, Object attributeValue); @Override Model addAttribute(Object attributeValue); @Override Model addAllAttributes(Collection<?> attributeValues); @Override Model addAllAttributes(Map<String, ?> attributes); @Override Model mergeAttributes(Map<String, ?> attributes); @Override boolean containsAttribute(String attributeName); @Override Map<String, Object> asMap(); }### Answer: @Test public void testCallsToContainsAttributeDoNotLockOtherReadOperations() throws ExecutionException, InterruptedException { assertFirstReadOperationDoesNotBlockSecondReadOperation( model -> model.containsAttribute("read1"), model -> model.containsAttribute("read2")); assertFirstReadOperationDoesNotBlockSecondReadOperation( model -> model.containsAttribute("read"), Model::asMap); } @Test public void testCallsToAsMapDoNotLockOtherReadOperations() throws ExecutionException, InterruptedException { assertFirstReadOperationDoesNotBlockSecondReadOperation( Model::asMap, model -> model.containsAttribute("read")); } @Test public void testThatTheTestMechanismWorks() throws ExecutionException, InterruptedException { try { assertFirstOperationBlocksSecondOperationUntilComplete( model -> model.containsAttribute("read1"), model -> model.containsAttribute("read2"), ReadWriteLockTestHelper::isReadLocked, ReadWriteLockTestHelper::isReadLocked); fail("2 read operations should not block each other and therefore there must be a problem with the test mechanism"); } catch (AssertionError e) { } }
### Question: ThreadsafeModel implements Model { @Override public Model addAllAttributes(Collection<?> attributeValues) { return withWriteLock(() -> model.addAllAttributes(attributeValues)); } ThreadsafeModel(Model model); @Override Model addAttribute(String attributeName, Object attributeValue); @Override Model addAttribute(Object attributeValue); @Override Model addAllAttributes(Collection<?> attributeValues); @Override Model addAllAttributes(Map<String, ?> attributes); @Override Model mergeAttributes(Map<String, ?> attributes); @Override boolean containsAttribute(String attributeName); @Override Map<String, Object> asMap(); }### Answer: @Test public void testCallsToAddAllAttributesLocksReadAccessUntilComplete() throws ExecutionException, InterruptedException { assertFirstOperationBlocksSecondOperationUntilComplete( model -> model.addAllAttributes(singletonList("write")), Model::asMap, ReadWriteLockTestHelper::isWriteLocked, ReadWriteLockTestHelper::isReadLocked); }
### Question: ThreadsafeModel implements Model { @Override public Model addAttribute(String attributeName, Object attributeValue) { return withWriteLock(() -> model.addAttribute(attributeName, attributeValue)); } ThreadsafeModel(Model model); @Override Model addAttribute(String attributeName, Object attributeValue); @Override Model addAttribute(Object attributeValue); @Override Model addAllAttributes(Collection<?> attributeValues); @Override Model addAllAttributes(Map<String, ?> attributes); @Override Model mergeAttributes(Map<String, ?> attributes); @Override boolean containsAttribute(String attributeName); @Override Map<String, Object> asMap(); }### Answer: @Test public void testCallsToAddAttributeLocksWriteAccessUntilComplete() throws ExecutionException, InterruptedException { assertFirstOperationBlocksSecondOperationUntilComplete( model -> model.addAttribute("write1"), model -> model.addAttribute("write2"), ReadWriteLockTestHelper::isWriteLocked, ReadWriteLockTestHelper::isWriteLocked); }
### Question: RestCacheMethodInterceptor implements MethodInterceptor { public RestCacheMethodInterceptor setUidSupplier(RestCacheUuidSupplier uidSupplier) { this.uidSupplier = uidSupplier; return this; } RestCacheUuidSupplier getUidSupplier(); RestCacheMethodInterceptor setUidSupplier(RestCacheUuidSupplier uidSupplier); void invalidate(); @Override Object invoke(MethodInvocation invocation); }### Answer: @Test public void testResultsCached() { final TestClassImpl base = new TestClassImpl(); final InvocationHandler handler = forBaseWithInterceptor(base, new RestCacheMethodInterceptor().setUidSupplier(() -> "1")); TestClass proxy = (TestClass) Proxy.newProxyInstance(TestClass.class.getClassLoader(), new Class[]{TestClass.class}, handler); proxy.method1(); proxy.method1(); proxy.method1(); Assert.assertEquals(1, base.numberTimesMethod1Called); proxy.method2(1); proxy.method2(1); proxy.method2(1); Assert.assertEquals(1, base.numberTimesMethod2Called); proxy.method2(2); Assert.assertEquals(2, base.numberTimesMethod2Called); proxy.method2(1); Assert.assertEquals(2, base.numberTimesMethod2Called); } @Test public void testResultsCachedPerUid() { final TestClassImpl base = new TestClassImpl(); final UidSupplierImpl uidSupplier = new UidSupplierImpl().setUid("a"); final InvocationHandler handler = forBaseWithInterceptor(base, new RestCacheMethodInterceptor().setUidSupplier(uidSupplier)); final TestClass proxy = (TestClass) Proxy.newProxyInstance(TestClass.class.getClassLoader(), new Class[]{TestClass.class}, handler); proxy.method1(); proxy.method1(); proxy.method1(); Assert.assertEquals(1, base.numberTimesMethod1Called); uidSupplier.setUid("b"); uidSupplier.setUid("b"); uidSupplier.setUid("b"); proxy.method1(); Assert.assertEquals(2, base.numberTimesMethod1Called); }
### Question: FormInputController { @DeleteMapping("/{id}") public RestResult<Void> delete(@PathVariable("id") Long id) { return formInputService.delete(id).toDeleteResponse(); } @GetMapping("/{id}") RestResult<FormInputResource> findOne(@PathVariable("id") Long id); @GetMapping("/find-by-question-id/{questionId}") RestResult<List<FormInputResource>> findByQuestionId(@PathVariable("questionId") Long questionId); @GetMapping("find-by-question-id/{questionId}/scope/{scope}") RestResult<List<FormInputResource>> findByQuestionIdAndScope(@PathVariable("questionId") Long questionId, @PathVariable("scope") FormInputScope scope); @GetMapping("/find-by-competition-id/{competitionId}") RestResult<List<FormInputResource>> findByCompetitionId(@PathVariable("competitionId") Long competitionId); @GetMapping("/find-by-competition-id/{competitionId}/scope/{scope}") RestResult<List<FormInputResource>> findByCompetitionIdAndScope(@PathVariable("competitionId") Long competitionId, @PathVariable("scope") FormInputScope scope); @DeleteMapping("/{id}") RestResult<Void> delete(@PathVariable("id") Long id); @GetMapping(value = "/file/{formInputId}", produces = "application/json") @ResponseBody ResponseEntity<Object> downloadFile(@PathVariable long formInputId); @GetMapping(value = "/file-details/{formInputId}", produces = "application/json") RestResult<FileEntryResource> findFile(@PathVariable long formInputId); }### Answer: @Test public void testDelete() throws Exception { Long formInputId = 1L; when(formInputServiceMock.delete(formInputId)).thenReturn(serviceSuccess()); mockMvc.perform(RestDocumentationRequestBuilders.delete("/forminput/{id}", formInputId)) .andExpect(status().is2xxSuccessful()); }
### Question: AlertMessageHandlerInterceptor extends HandlerInterceptorAdapter { @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) { if (modelAndView != null) { addAlertMessages(modelAndView); } } @Override void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView); }### Answer: @Test public void alertsPresent() { AlertResource alert = new AlertResource(); when(alertRestService.findAllVisible()).thenReturn(restSuccess(asList(alert))); ModelAndView mav = new ModelAndView(); interceptor.postHandle(null, null, null, mav); assertTrue(mav.getModelMap().containsKey("alertMessages")); assertEquals(1, ((List<AlertResource>)mav.getModelMap().get("alertMessages")).size()); assertEquals(alert, ((List<AlertResource>)mav.getModelMap().get("alertMessages")).get(0)); } @Test public void alertsNotPresent() { when(alertRestService.findAllVisible()).thenReturn(restSuccess(asList())); ModelAndView mav = new ModelAndView(); interceptor.postHandle(null, null, null, mav); assertFalse(mav.getModelMap().containsKey("alertMessages")); } @Test public void alertsServiceNotSuccessful() { when(alertRestService.findAllVisible()).thenReturn(restFailure(new Error("some.key", HttpStatus.NOT_FOUND))); ModelAndView mav = new ModelAndView(); interceptor.postHandle(null, null, null, mav); assertFalse(mav.getModelMap().containsKey("alertMessages")); }
### Question: FileDownloadControllerUtils { public static ResponseEntity<ByteArrayResource> getFileResponseEntity(ByteArrayResource resource, FileEntryResource fileEntry) { HttpHeaders httpHeaders = new HttpHeaders(); httpHeaders.setContentLength(resource.contentLength()); httpHeaders.setContentType(MediaType.parseMediaType(fileEntry.getMediaType())); if(StringUtils.hasText(fileEntry.getName())) { httpHeaders.add("Content-Disposition", "inline; filename=\"" + fileEntry.getName() + "\""); } return new ResponseEntity<>(resource, httpHeaders, HttpStatus.OK); } private FileDownloadControllerUtils(); static ResponseEntity<ByteArrayResource> getFileResponseEntity(ByteArrayResource resource, FileEntryResource fileEntry); }### Answer: @Test public void fileResponseEntity() { ByteArrayResource resource = new ByteArrayResource("somebytes".getBytes()); FileEntryResource fileEntry = new FileEntryResource(); fileEntry.setMediaType(MediaType.IMAGE_JPEG_VALUE); fileEntry.setName("name"); ResponseEntity<ByteArrayResource> result = FileDownloadControllerUtils.getFileResponseEntity(resource, fileEntry); assertEquals("inline; filename=\"name\"", result.getHeaders().get("Content-Disposition").get(0)); assertEquals("9", result.getHeaders().get("Content-Length").get(0)); assertEquals(MediaType.IMAGE_JPEG_VALUE, result.getHeaders().get("Content-Type").get(0)); assertArrayEquals("somebytes".getBytes(), result.getBody().getByteArray()); } @Test public void fileResponseEntityMissingName() { ByteArrayResource resource = new ByteArrayResource("somebytes".getBytes()); FileEntryResource fileEntry = new FileEntryResource(); fileEntry.setMediaType(MediaType.IMAGE_JPEG_VALUE); ResponseEntity<ByteArrayResource> result = FileDownloadControllerUtils.getFileResponseEntity(resource, fileEntry); assertNull(result.getHeaders().get("Content-Disposition")); assertEquals("9", result.getHeaders().get("Content-Length").get(0)); assertEquals(MediaType.IMAGE_JPEG_VALUE, result.getHeaders().get("Content-Type").get(0)); assertArrayEquals("somebytes".getBytes(), result.getBody().getByteArray()); }
### Question: RejectionReasonFormatter implements Formatter<RejectionReasonResource> { @Override public RejectionReasonResource parse(String text, Locale locale) throws ParseException { RejectionReasonResource rejectionReasonResource = new RejectionReasonResource(); rejectionReasonResource.setId(Long.valueOf(text)); return rejectionReasonResource; } @Override RejectionReasonResource parse(String text, Locale locale); @Override String print(RejectionReasonResource object, Locale locale); }### Answer: @Test public void parse() throws Exception { RejectionReasonFormatter formatter = new RejectionReasonFormatter(); String text = "1"; RejectionReasonResource expected = new RejectionReasonResource(); expected.setId(1L); assertEquals(expected, formatter.parse(text, Locale.UK)); }
### Question: RejectionReasonFormatter implements Formatter<RejectionReasonResource> { @Override public String print(RejectionReasonResource object, Locale locale) { return object != null ? object.getId().toString() : ""; } @Override RejectionReasonResource parse(String text, Locale locale); @Override String print(RejectionReasonResource object, Locale locale); }### Answer: @Test public void print() { RejectionReasonFormatter formatter = new RejectionReasonFormatter(); RejectionReasonResource reason = newRejectionReasonResource() .with(id(1L)) .withReason("Reason") .withActive(TRUE) .withPriority(1) .build(); assertEquals("1", formatter.print(reason, Locale.UK)); }
### Question: ApplicationSummaryViewModel implements BaseAnalyticsViewModel { public boolean isKtpCompetition() { return ktpCompetition; } ApplicationSummaryViewModel(ApplicationReadOnlyViewModel applicationReadOnlyViewModel, ApplicationResource application, CompetitionResource competition, boolean projectWithdrawn, InterviewFeedbackViewModel interviewFeedbackViewModel); InterviewFeedbackViewModel getInterviewFeedbackViewModel(); @Override Long getApplicationId(); ApplicationReadOnlyViewModel getApplicationReadOnlyViewModel(); ApplicationResource getApplication(); CompetitionResource getCompetition(); boolean isProjectWithdrawn(); String getCompetitionName(); String getApplicationName(); LocalDate getStartDate(); Long getDuration(); Boolean getResubmission(); boolean isCanSelectInnovationArea(); String getInnovationAreaName(); String getPreviousApplicationNumber(); String getPreviousApplicationTitle(); boolean isKtpCompetition(); }### Answer: @Test public void testKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP) .withInnovationAreas(Collections.emptySet()).build(); InnovationAreaResource innovationAreaResource = InnovationAreaResourceBuilder.newInnovationAreaResource().build(); ApplicationResource applicationResource = ApplicationResourceBuilder.newApplicationResource() .withInnovationArea(innovationAreaResource).build(); ApplicationSummaryViewModel viewModel = new ApplicationSummaryViewModel(null, applicationResource, competitionResource, false, null); assertTrue(viewModel.isKtpCompetition()); }
### Question: FormInputServiceImpl extends BaseTransactionalService implements FormInputService { @Override public ServiceResult<FileEntryResource> findFile(long formInputId) { return findFormInputEntity(formInputId).andOnSuccess(formInput -> ofNullable(formInput.getFile()) .map(FileEntry::getId) .map(fileEntryService::findOne) .orElse(serviceSuccess(null))); } @Override ServiceResult<FormInputResource> findFormInput(long id); @Override ServiceResult<List<FormInputResource>> findByQuestionId(long questionId); @Override @Cacheable(cacheNames="formInputByQuestionAndScope", key = "T(java.lang.String).format('formInputByQuestionAndScope:%d:%s', #questionId, #scope.name())", unless = "!T(org.innovateuk.ifs.cache.CacheHelper).cacheResultIfCompetitionIsOpen(#result)") ServiceResult<List<FormInputResource>> findByQuestionIdAndScope(long questionId, FormInputScope scope); @Override ServiceResult<List<FormInputResource>> findByCompetitionId(long competitionId); @Override ServiceResult<List<FormInputResource>> findByCompetitionIdAndScope(long competitionId, FormInputScope scope); @Override @Transactional ServiceResult<Void> delete(long id); @Override ServiceResult<FileAndContents> downloadFile(long formInputId); @Override ServiceResult<FileEntryResource> findFile(long formInputId); }### Answer: @Test public void findTemplateFile() throws Exception { long formInputId = 1L; FileEntry fileEntry = newFileEntry().build(); FormInput formInput = newFormInput() .withFile(fileEntry) .build(); FileEntryResource fileEntryResource = newFileEntryResource().build(); when(formInputRepository.findById(formInputId)).thenReturn(Optional.of(formInput)); when(fileEntryServiceMock.findOne(fileEntry.getId())).thenReturn(serviceSuccess(fileEntryResource)); FileEntryResource response = service.findFile(formInputId).getSuccess(); assertEquals(fileEntryResource, response); }
### Question: GenericQuestionApplicationFormValidator { private void validateTextArea(GenericQuestionApplicationForm form, BindingResult bindingResult) { if (form.isTextAreaActive() && form.getAnswer().trim().length() <= 0) { bindingResult.rejectValue("answer", "validation.field.please.enter.some.text"); } } void validate(GenericQuestionApplicationForm form, BindingResult bindingResult); }### Answer: @Test public void validateTextArea() { GenericQuestionApplicationForm form = new GenericQuestionApplicationForm(); form.setAnswer(""); form.setTextAreaActive(true); form.setMultipleChoiceOptionsActive(false); validator.validate(form, bindingResult); assertTrue(bindingResult.hasErrors()); Assert.assertEquals(1, bindingResult.getErrorCount()); FieldError actualError = (FieldError) bindingResult.getAllErrors().get(0); assertEquals("validation.field.please.enter.some.text", actualError.getCode()); assertEquals("answer", actualError.getField()); }
### Question: GenericQuestionApplicationFormValidator { private void validateMultipleChoiceOptions(GenericQuestionApplicationForm form, BindingResult bindingResult) { if (form.isMultipleChoiceOptionsActive() && form.getMultipleChoiceOptionId() == null) { bindingResult.rejectValue("multipleChoiceOptionId", "validation.multiple.choice.required"); } } void validate(GenericQuestionApplicationForm form, BindingResult bindingResult); }### Answer: @Test public void validateMultipleChoiceOptions() { GenericQuestionApplicationForm form = new GenericQuestionApplicationForm(); form.setAnswer(""); form.setTextAreaActive(false); form.setMultipleChoiceOptionsActive(true); validator.validate(form, bindingResult); assertTrue(bindingResult.hasErrors()); Assert.assertEquals(1, bindingResult.getErrorCount()); FieldError actualError = (FieldError) bindingResult.getAllErrors().get(0); assertEquals("validation.multiple.choice.required", actualError.getCode()); assertEquals("multipleChoiceOptionId", actualError.getField()); }
### Question: YourProjectLocationFormPopulator { public YourProjectLocationForm populate(long applicationId, long organisationId) { ApplicationFinanceResource applicationFinance = applicationFinanceRestService.getApplicationFinance(applicationId, organisationId).getSuccess(); String postcode = applicationFinance.getWorkPostcode(); String town = applicationFinance.getInternationalLocation(); return new YourProjectLocationForm(postcode, town); } @Autowired YourProjectLocationFormPopulator(ApplicationFinanceRestService applicationFinanceRestService); YourProjectLocationForm populate(long applicationId, long organisationId); }### Answer: @Test public void populate() { long applicationId = 123L; long organisationId = 456L; String postcode = "S2 5AB"; when(applicationFinanceRestServiceMock.getApplicationFinance(applicationId, organisationId)). thenReturn(restSuccess(newApplicationFinanceResource().withWorkPostcode(postcode).build())); YourProjectLocationForm form = populator.populate(applicationId, organisationId); assertThat(form.getPostcode()).isEqualTo(postcode); verify(applicationFinanceRestServiceMock, times(1)).getApplicationFinance(applicationId, organisationId); }
### Question: CommonYourFinancesViewModelPopulator { public CommonYourProjectFinancesViewModel populate(long organisationId, long applicationId, long sectionId, UserResource user) { ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess(); OrganisationResource organisation = organisationRestService.getOrganisationById(organisationId).getSuccess(); List<Long> completedSectionIds = sectionService.getCompleted(applicationId, organisationId); boolean sectionMarkedAsComplete = completedSectionIds.contains(sectionId); boolean userCanEdit = !(user.isInternalUser() || user.hasRole(Role.EXTERNAL_FINANCE)) && userRestService.findProcessRole(user.getId(), applicationId).getOptionalSuccessObject() .map(role -> role.getOrganisationId() != null && role.getOrganisationId().equals(organisationId)) .orElse(false); boolean open = userCanEdit && application.isOpen() && competition.isOpen(); return new CommonYourProjectFinancesViewModel( getYourFinancesUrl(applicationId, organisationId), application.getCompetitionName(), application.getName(), applicationId, sectionId, open, competition.isH2020(), sectionMarkedAsComplete, competition.isProcurement(), organisation.isInternational()); } CommonYourProjectFinancesViewModel populate(long organisationId, long applicationId, long sectionId, UserResource user); }### Answer: @Test public void populate() { boolean internalUser = false; List<Long> sectionsMarkedAsComplete = asList(111L, 333L); ApplicationState applicationState = ApplicationState.OPENED; CompetitionStatus competitionState = CompetitionStatus.OPEN; assertViewModelPopulatedOk( internalUser, sectionsMarkedAsComplete, applicationState, competitionState, expectViewModelIsIncomplete, expectViewModelIsOpen, expectViewModelIsEditable, expectedExternalUserFinanceUrl); }
### Question: ApplicationCreationAuthenticatedController { @GetMapping("/{competitionId}") public String view(Model model, @PathVariable(COMPETITION_ID) long competitionId, UserResource user, HttpServletResponse response) { Boolean userHasApplication = userService.userHasApplicationForCompetition(user.getId(), competitionId); if (Boolean.TRUE.equals(userHasApplication)) { model.addAttribute(COMPETITION_ID, competitionId); model.addAttribute(FORM_NAME, new ApplicationCreationAuthenticatedForm()); return "create-application/confirm-new-application"; } else { return redirectToOrganisationCreation(competitionId, response); } } @GetMapping("/{competitionId}") String view(Model model, @PathVariable(COMPETITION_ID) long competitionId, UserResource user, HttpServletResponse response); @PostMapping("/{competitionId}") String post(@PathVariable(COMPETITION_ID) long competitionId, @Valid @ModelAttribute(FORM_NAME) ApplicationCreationAuthenticatedForm form, BindingResult bindingResult, ValidationHandler validationHandler, HttpServletResponse response); }### Answer: @Test public void getRequestWithExistingApplication() throws Exception { when(userService.userHasApplicationForCompetition(loggedInUser.getId(), 1L)).thenReturn(true); mockMvc.perform(get("/application/create-authenticated/{competitionId}", 1L)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("create-application/confirm-new-application")); verify(userService).userHasApplicationForCompetition(loggedInUser.getId(), 1L); }
### Question: ApplicationCreationController { @GetMapping("/start-application/{competitionId}") public String checkEligibility(Model model, @PathVariable(COMPETITION_ID) Long competitionId, HttpServletResponse response) { PublicContentItemResource publicContentItem = publicContentItemRestService.getItemByCompetitionId(competitionId).getSuccess(); if (!isCompetitionReady(publicContentItem)) { return "redirect:/competition/search"; } model.addAttribute(COMPETITION_ID, competitionId); registrationCookieService.deleteAllRegistrationJourneyCookies(response); registrationCookieService.saveToCompetitionIdCookie(competitionId, response); return "create-application/start-application"; } @GetMapping("/start-application/{competitionId}") String checkEligibility(Model model, @PathVariable(COMPETITION_ID) Long competitionId, HttpServletResponse response); static final String COMPETITION_ID; }### Answer: @Test public void checkEligibility() throws Exception { long competitionId = 1L; PublicContentItemResource publicContentItem = newPublicContentItemResource() .withCompetitionOpenDate(ZonedDateTime.now().minusDays(1)) .withCompetitionCloseDate(ZonedDateTime.now().plusDays(1)) .withNonIfs(false) .build(); when(publicContentItemRestService.getItemByCompetitionId(competitionId)).thenReturn(restSuccess(publicContentItem)); MvcResult result = mockMvc.perform(get("/application/create/start-application/{competitionId}", competitionId)) .andExpect(status().is2xxSuccessful()) .andExpect(view().name("create-application/start-application")) .andReturn(); verify(registrationCookieService, times(1)).deleteAllRegistrationJourneyCookies(any(HttpServletResponse.class)); verify(registrationCookieService, times(1)).saveToCompetitionIdCookie(anyLong(), any(HttpServletResponse.class)); }
### Question: LoginController { @GetMapping("/" + LOGIN_BASE + "/" + RESET_PASSWORD) public String requestPasswordReset(ResetPasswordRequestForm resetPasswordRequestForm, Model model) { model.addAttribute("resetPasswordRequestForm", resetPasswordRequestForm); return LOGIN_BASE + "/" + RESET_PASSWORD; } LoginController(UserService userService, UserRestService userRestService); @GetMapping("/" + LOGIN_BASE + "/" + RESET_PASSWORD) String requestPasswordReset(ResetPasswordRequestForm resetPasswordRequestForm, Model model); @PostMapping("/" + LOGIN_BASE + "/" + RESET_PASSWORD) String requestPasswordResetPost(@ModelAttribute @Valid ResetPasswordRequestForm resetPasswordRequestForm, BindingResult bindingResult, Model model); @GetMapping("/" + LOGIN_BASE + "/" + RESET_PASSWORD + "/hash/{hash}") String resetPassword(@PathVariable("hash") String hash, @ModelAttribute(binding = false) ResetPasswordForm resetPasswordForm, Model model, HttpServletRequest request); @PostMapping("/" + LOGIN_BASE + "/" + RESET_PASSWORD + "/hash/{hash}") String resetPasswordPost(@PathVariable("hash") String hash, @Valid @ModelAttribute ResetPasswordForm resetPasswordForm, BindingResult bindingResult); static final String LOGIN_BASE; static final String RESET_PASSWORD; static final String RESET_PASSWORD_FORM; static final String RESET_PASSWORD_NOTIFICATION_SEND; static final String PASSWORD_CHANGED; }### Answer: @Test public void testRequestPasswordReset() throws Exception { mockMvc.perform(get("/" + LoginController.LOGIN_BASE + "/" + LoginController.RESET_PASSWORD)) .andExpect(status().isOk()) .andExpect(view().name(LoginController.LOGIN_BASE + "/" + LoginController.RESET_PASSWORD)); }
### Question: UserProfilePopulator { public UserProfileViewModel populate(UserResource user) { List<OrganisationResource> organisations = organisationRestService.getAllByUserId(user.getId()).getSuccess(); Set<OrganisationProfileViewModel> organisationViewModels = simpleMapSet(organisations, this::toOrganisationViewModel); String name; if (user.getTitle() != null) { name = user.getTitle() + " " + user.getName().trim(); } else { name = user.getName(); } return new UserProfileViewModel(name, user.getPhoneNumber(), user.getEmail(), user.getAllowMarketingEmails(), organisationViewModels, user.hasAnyRoles(MONITORING_OFFICER)); } UserProfileViewModel populate(UserResource user); }### Answer: @Test public void populate() { UserResource user = newUserResource() .withFirstName("Steve") .withLastName("Smith") .withEmail("[email protected]") .build(); List<OrganisationResource> organisations = newOrganisationResource() .withName("organisation") .withOrganisationTypeName("Type") .withCompaniesHouseNumber("123") .build(1); when(organisationRestService.getAllByUserId(user.getId())).thenReturn(restSuccess(organisations)); UserProfileViewModel actual = target.populate(user); assertEquals(actual.getName(), user.getName()); assertEquals(actual.getEmailAddress(), user.getEmail()); assertEquals(actual.getPhoneNumber(), user.getPhoneNumber()); assertEquals(actual.getOrganisations().iterator().next().getName(), organisations.get(0).getName()); assertEquals(actual.getOrganisations().iterator().next().getRegistrationNumber(), organisations.get(0).getCompaniesHouseNumber()); assertEquals(actual.getOrganisations().iterator().next().getType(), organisations.get(0).getOrganisationTypeName()); }
### Question: ApplicantDashboardController { @SecuredBySpring(value = "ApplicantDashboardController", description = "applicant and kta has permission to view their own dashboard") @PreAuthorize("hasAnyAuthority('applicant', 'knowledge_transfer_adviser')") @GetMapping @NavigationRoot public String dashboard(Model model, UserResource user) { model.addAttribute("model", applicantDashboardPopulator.populate(user.getId())); return "applicant-dashboard"; } @SecuredBySpring(value = "ApplicantDashboardController", description = "applicant and kta has permission to view their own dashboard") @PreAuthorize("hasAnyAuthority('applicant', 'knowledge_transfer_adviser')") @GetMapping @NavigationRoot String dashboard(Model model, UserResource user); @PostMapping(params = "hide-application") String hideApplication(@RequestParam("hide-application") long applicationId, UserResource user); @PostMapping(params = "delete-application") String deleteApplication(@RequestParam("delete-application") long applicationId); }### Answer: @Test public void dashboard() throws Exception { ApplicantDashboardViewModel viewModel = mock(ApplicantDashboardViewModel.class); when(populator.populate(loggedInUser.getId())).thenReturn(viewModel); mockMvc.perform(get("/applicant/dashboard")) .andExpect(status().isOk()) .andExpect(view().name("applicant-dashboard")) .andExpect(model().attribute("model", viewModel)); }
### Question: ApplicantDashboardController { @PostMapping(params = "hide-application") public String hideApplication(@RequestParam("hide-application") long applicationId, UserResource user) { applicationRestService.hideApplication(applicationId, user.getId()); return format("redirect:/applicant/dashboard"); } @SecuredBySpring(value = "ApplicantDashboardController", description = "applicant and kta has permission to view their own dashboard") @PreAuthorize("hasAnyAuthority('applicant', 'knowledge_transfer_adviser')") @GetMapping @NavigationRoot String dashboard(Model model, UserResource user); @PostMapping(params = "hide-application") String hideApplication(@RequestParam("hide-application") long applicationId, UserResource user); @PostMapping(params = "delete-application") String deleteApplication(@RequestParam("delete-application") long applicationId); }### Answer: @Test public void hideApplication() throws Exception { UserResource collaborator = this.collaborator; setLoggedInUser(collaborator); long applicationId = 1L; long userId = 1L; when(applicationRestService.hideApplication(applicationId, userId)).thenReturn(RestResult.restSuccess()); mockMvc.perform(post("/applicant/dashboard") .param("hide-application", valueOf(applicationId))) .andExpect(status().is3xxRedirection()); }
### Question: ApplicantDashboardController { @PostMapping(params = "delete-application") public String deleteApplication(@RequestParam("delete-application") long applicationId) { applicationRestService.deleteApplication(applicationId); return format("redirect:/applicant/dashboard"); } @SecuredBySpring(value = "ApplicantDashboardController", description = "applicant and kta has permission to view their own dashboard") @PreAuthorize("hasAnyAuthority('applicant', 'knowledge_transfer_adviser')") @GetMapping @NavigationRoot String dashboard(Model model, UserResource user); @PostMapping(params = "hide-application") String hideApplication(@RequestParam("hide-application") long applicationId, UserResource user); @PostMapping(params = "delete-application") String deleteApplication(@RequestParam("delete-application") long applicationId); }### Answer: @Test public void deleteApplication() throws Exception { setLoggedInUser(applicant); long applicationId = 1L; when(applicationRestService.deleteApplication(applicationId)).thenReturn(RestResult.restSuccess()); mockMvc.perform(post("/applicant/dashboard").param("delete-application", valueOf(applicationId))) .andExpect(status().is3xxRedirection()); }
### Question: SiteTermsController { @PreAuthorize("permitAll") @GetMapping("terms-and-conditions") public String termsAndConditions() { SiteTermsAndConditionsResource siteTermsAndConditions = termsAndConditionsRestService .getLatestSiteTermsAndConditions().getSuccess(); return format("content/%s", siteTermsAndConditions.getTemplate()); } @PreAuthorize("permitAll") @GetMapping("terms-and-conditions") String termsAndConditions(); @GetMapping("new-terms-and-conditions") String newTermsAndConditions(@ModelAttribute(name = "form") NewSiteTermsAndConditionsForm form); @PostMapping("new-terms-and-conditions") String agreeNewTermsAndConditions(HttpServletRequest request, HttpServletResponse response, UserResource loggedInUser, @Valid @ModelAttribute(name = "form") NewSiteTermsAndConditionsForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler); }### Answer: @Test public void termsAndConditions() throws Exception { SiteTermsAndConditionsResource siteTermsAndConditionsResource = newSiteTermsAndConditionsResource() .withTemplate("test-terms-and-conditions") .build(); when(termsAndConditionsRestService.getLatestSiteTermsAndConditions()).thenReturn( restSuccess(siteTermsAndConditionsResource)); mockMvc.perform(get("/info/terms-and-conditions")) .andExpect(status().isOk()) .andExpect(view().name("content/test-terms-and-conditions")); }
### Question: SiteTermsController { @GetMapping("new-terms-and-conditions") public String newTermsAndConditions(@ModelAttribute(name = "form") NewSiteTermsAndConditionsForm form) { return "content/new-terms-and-conditions"; } @PreAuthorize("permitAll") @GetMapping("terms-and-conditions") String termsAndConditions(); @GetMapping("new-terms-and-conditions") String newTermsAndConditions(@ModelAttribute(name = "form") NewSiteTermsAndConditionsForm form); @PostMapping("new-terms-and-conditions") String agreeNewTermsAndConditions(HttpServletRequest request, HttpServletResponse response, UserResource loggedInUser, @Valid @ModelAttribute(name = "form") NewSiteTermsAndConditionsForm form, @SuppressWarnings("unused") BindingResult bindingResult, ValidationHandler validationHandler); }### Answer: @Test public void newTermsAndConditions() throws Exception { NewSiteTermsAndConditionsForm expectedForm = new NewSiteTermsAndConditionsForm(); mockMvc.perform(get("/info/new-terms-and-conditions")) .andExpect(status().isOk()) .andExpect(model().attribute("form", expectedForm)) .andExpect(view().name("content/new-terms-and-conditions")); }
### Question: StaticContentController { @GetMapping("contact") public String contact() { return "content/contact"; } @GetMapping("contact") String contact(); @GetMapping("cookies") String cookies(); @GetMapping("accessibility") String accessibility(); }### Answer: @Test public void contact() throws Exception { mockMvc.perform(get("/info/contact")) .andExpect(status().isOk()) .andExpect(view().name("content/contact")); }
### Question: StaticContentController { @GetMapping("cookies") public String cookies() { return "content/cookies"; } @GetMapping("contact") String contact(); @GetMapping("cookies") String cookies(); @GetMapping("accessibility") String accessibility(); }### Answer: @Test public void cookies() throws Exception { mockMvc.perform(get("/info/cookies")) .andExpect(status().isOk()) .andExpect(view().name("content/cookies")); }
### Question: StaticContentController { @GetMapping("accessibility") public String accessibility() { return "content/accessibility"; } @GetMapping("contact") String contact(); @GetMapping("cookies") String cookies(); @GetMapping("accessibility") String accessibility(); }### Answer: @Test public void accessibility() throws Exception { mockMvc.perform(get("/info/accessibility")) .andExpect(status().isOk()) .andExpect(view().name("content/accessibility")); }
### Question: RegistrationController { @GetMapping("/resend-email-verification") public String resendEmailVerification(final ResendEmailVerificationForm resendEmailVerificationForm, final Model model) { model.addAttribute("resendEmailVerificationForm", resendEmailVerificationForm); return "registration/resend-email-verification"; } void setValidator(Validator validator); @GetMapping("/success") String registrationSuccessful(Model model, @RequestHeader(value = "referer", required = false) final String referer, final HttpServletRequest request, HttpServletResponse response); @GetMapping("/verified") String verificationSuccessful(final HttpServletRequest request, final HttpServletResponse response); @GetMapping("/verify-email/{hash}") String verifyEmailAddress(@PathVariable("hash") final String hash, final HttpServletResponse response); @GetMapping("/register") String registerForm(@ModelAttribute("form") RegistrationForm registrationForm, Model model, UserResource user, HttpServletRequest request, HttpServletResponse response); @PostMapping("/register") String registerFormSubmit(@Validated({Default.class, PhoneNumberValidationGroup.class, TermsValidationGroup.class}) @ModelAttribute("form") RegistrationForm registrationForm, BindingResult bindingResult, HttpServletResponse response, UserResource user, HttpServletRequest request, Model model); @GetMapping("/duplicate-project-organisation") String displayErrorPage(HttpServletRequest request, Model model); @GetMapping("/resend-email-verification") String resendEmailVerification(final ResendEmailVerificationForm resendEmailVerificationForm, final Model model); @PostMapping("/resend-email-verification") String resendEmailVerification(@Valid final ResendEmailVerificationForm resendEmailVerificationForm, final BindingResult bindingResult, final Model model); static final String BASE_URL; }### Answer: @Test public void resendEmailVerification() throws Exception { mockMvc.perform(get("/registration/resend-email-verification")) .andExpect(status().isOk()) .andExpect(view().name("registration/resend-email-verification")); }
### Question: AcceptRejectApplicationKtaInviteModelPopulator { public AcceptRejectApplicationKtaInviteViewModel populateModel(ApplicationKtaInviteResource invite) { return new AcceptRejectApplicationKtaInviteViewModel(invite.getApplication(), invite.getApplicationName(), invite.getCompetitionName(), invite.getLeadOrganisationName(), invite.getLeadApplicant(), invite.getHash()); } AcceptRejectApplicationKtaInviteViewModel populateModel(ApplicationKtaInviteResource invite); }### Answer: @Test public void populateModel() { long applicationId= 123L; ApplicationKtaInviteResource invite = newApplicationKtaInviteResource() .withApplication(applicationId) .withApplicationName("KTP Application") .withCompetitionName("KTP Competition") .withLeadApplicant("Steve Smith") .withLeadOrganisationName("Empire Ltd") .withHash("hash123") .withStatus(InviteStatus.SENT) .build(); AcceptRejectApplicationKtaInviteViewModel model = new AcceptRejectApplicationKtaInviteModelPopulator().populateModel(invite); assertEquals(invite.getCompetitionName(), model.getCompetitionName()); assertEquals(invite.getLeadOrganisationName(), model.getLeadOrganisationName()); assertEquals(invite.getLeadApplicant(), model.getLeadApplicantName()); assertEquals(invite.getApplicationName(), model.getApplicationName()); assertEquals(invite.getApplication(), model.getApplicationId()); assertEquals(invite.getHash(), model.getHash()); }
### Question: UpcomingCompetitionViewModel { public boolean isKtpCompetition() { return ktpCompetition; } UpcomingCompetitionViewModel(CompetitionResource competitionResource, CompetitionAssessmentConfigResource competitionAssessmentConfigResource); long getCompetitionId(); String getCompetitionName(); void setCompetitionName(String competitionName); ZonedDateTime getAssessmentPeriodDateFrom(); void setAssessmentPeriodDateFrom(ZonedDateTime assessmentPeriodDateFrom); ZonedDateTime getAssessmentPeriodDateTo(); void setAssessmentPeriodDateTo(ZonedDateTime assessmentPeriodDateTo); ZonedDateTime getAssessorBriefingDate(); void setAssessorBriefingDate(ZonedDateTime assessorBriefingDate); BigDecimal getAssessorPay(); void setAssessorPay(BigDecimal assessorPay); boolean isKtpCompetition(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testNonKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.GRANT) .build(); CompetitionAssessmentConfigResource competitionAssessmentConfigResource = CompetitionAssessmentConfigResourceBuilder .newCompetitionAssessmentConfigResource().build(); UpcomingCompetitionViewModel viewModel = new UpcomingCompetitionViewModel(competitionResource, competitionAssessmentConfigResource); assertFalse(viewModel.isKtpCompetition()); } @Test public void testKtpCompetition() { CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP) .build(); CompetitionAssessmentConfigResource competitionAssessmentConfigResource = CompetitionAssessmentConfigResourceBuilder .newCompetitionAssessmentConfigResource().build(); UpcomingCompetitionViewModel viewModel = new UpcomingCompetitionViewModel(competitionResource, competitionAssessmentConfigResource); assertTrue(viewModel.isKtpCompetition()); }
### Question: AssessorProfileStatusViewModel { public boolean isSkillsComplete() { return skillsComplete; } AssessorProfileStatusViewModel(UserProfileStatusResource userProfileStatusResource, RoleProfileState roleProfileState); boolean isSkillsComplete(); boolean isAffiliationsComplete(); boolean isAgreementComplete(); boolean isComplete(); boolean displayBannerMessage(); String getBannerMessage(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void isSkillsComplete() { assertFalse(nothingCompleteProfileStatus.isSkillsComplete()); assertTrue(skillsCompleteProfileStatus.isSkillsComplete()); assertFalse(affiliationsCompleteProfileStatus.isSkillsComplete()); assertFalse(agreementCompleteProfileStatus.isSkillsComplete()); assertTrue(allCompleteProfileStatus.isSkillsComplete()); }
### Question: AssessorProfileStatusViewModel { public boolean isAffiliationsComplete() { return affiliationsComplete; } AssessorProfileStatusViewModel(UserProfileStatusResource userProfileStatusResource, RoleProfileState roleProfileState); boolean isSkillsComplete(); boolean isAffiliationsComplete(); boolean isAgreementComplete(); boolean isComplete(); boolean displayBannerMessage(); String getBannerMessage(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void isAffiliationsComplete() { assertFalse(nothingCompleteProfileStatus.isAffiliationsComplete()); assertFalse(skillsCompleteProfileStatus.isAffiliationsComplete()); assertTrue(affiliationsCompleteProfileStatus.isAffiliationsComplete()); assertFalse(agreementCompleteProfileStatus.isAffiliationsComplete()); assertTrue(allCompleteProfileStatus.isAffiliationsComplete()); }
### Question: AssessorProfileStatusViewModel { public boolean isAgreementComplete() { return agreementComplete; } AssessorProfileStatusViewModel(UserProfileStatusResource userProfileStatusResource, RoleProfileState roleProfileState); boolean isSkillsComplete(); boolean isAffiliationsComplete(); boolean isAgreementComplete(); boolean isComplete(); boolean displayBannerMessage(); String getBannerMessage(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void isAgreementComplete() { assertFalse(nothingCompleteProfileStatus.isAgreementComplete()); assertFalse(skillsCompleteProfileStatus.isAgreementComplete()); assertFalse(affiliationsCompleteProfileStatus.isAgreementComplete()); assertTrue(agreementCompleteProfileStatus.isAgreementComplete()); assertTrue(allCompleteProfileStatus.isAgreementComplete()); }
### Question: AssessorProfileStatusViewModel { public boolean isComplete() { return skillsComplete && affiliationsComplete && agreementComplete; } AssessorProfileStatusViewModel(UserProfileStatusResource userProfileStatusResource, RoleProfileState roleProfileState); boolean isSkillsComplete(); boolean isAffiliationsComplete(); boolean isAgreementComplete(); boolean isComplete(); boolean displayBannerMessage(); String getBannerMessage(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void isComplete() { assertFalse(nothingCompleteProfileStatus.isComplete()); assertFalse(skillsCompleteProfileStatus.isComplete()); assertFalse(affiliationsCompleteProfileStatus.isComplete()); assertFalse(agreementCompleteProfileStatus.isComplete()); assertTrue(allCompleteProfileStatus.isComplete()); }
### Question: AssessorProfileTravelController { @GetMapping public String getTravelAndSubsistence() { return "profile/travel"; } @GetMapping String getTravelAndSubsistence(); }### Answer: @Test public void getTravelAndSubsistence() throws Exception { mockMvc.perform(get("/profile/travel")) .andExpect(status().isOk()) .andExpect(view().name("profile/travel")); }
### Question: AssessorProfileAgreementController { @GetMapping public String getAgreement(Model model, UserResource loggedInUser) { ProfileAgreementResource profileAgreementResource = profileRestService.getProfileAgreement(loggedInUser.getId()).getSuccess(); return doViewAgreement(model, profileAgreementResource); } @GetMapping String getAgreement(Model model, UserResource loggedInUser); @PostMapping String submitAgreement(Model model, UserResource loggedInUser); }### Answer: @Test public void getAgreement() throws Exception { UserResource user = newUserResource().build(); setLoggedInUser(user); ZonedDateTime expectedAgreementSignedDate = ZonedDateTime.now(); String expectedText = "Agreement text..."; ProfileAgreementResource profileAgreementResource = newProfileAgreementResource() .withAgreementSignedDate(expectedAgreementSignedDate) .withCurrentAgreement(true) .withAgreement(newAgreementResource() .withText(expectedText) .build()) .build(); when(profileRestService.getProfileAgreement(user.getId())).thenReturn(restSuccess(profileAgreementResource)); AssessorProfileAgreementViewModel expectedViewModel = new AssessorProfileAgreementViewModel(); expectedViewModel.setCurrentAgreement(true); expectedViewModel.setAgreementSignedDate(expectedAgreementSignedDate); expectedViewModel.setText(expectedText); mockMvc.perform(get("/profile/agreement")) .andExpect(status().isOk()) .andExpect(model().hasNoErrors()) .andExpect(model().attribute("model", expectedViewModel)) .andExpect(view().name("profile/agreement")); verify(profileRestService, only()).getProfileAgreement(user.getId()); }
### Question: AssessorProfileAgreementController { @PostMapping public String submitAgreement(Model model, UserResource loggedInUser) { profileRestService.updateProfileAgreement(loggedInUser.getId()).getSuccess(); return "redirect:/assessor/dashboard"; } @GetMapping String getAgreement(Model model, UserResource loggedInUser); @PostMapping String submitAgreement(Model model, UserResource loggedInUser); }### Answer: @Test public void submitAgreement() throws Exception { UserResource user = newUserResource().build(); setLoggedInUser(user); when(profileRestService.updateProfileAgreement(user.getId())).thenReturn(restSuccess()); mockMvc.perform(post("/profile/agreement") .contentType(APPLICATION_FORM_URLENCODED) .param("agreesToTerms", "true")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/assessor/dashboard")); verify(profileRestService, only()).updateProfileAgreement(user.getId()); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public AssessmentResource getById(Long id) { return assessmentRestService.getById(id).getSuccess(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void getById() throws Exception { AssessmentResource expected = newAssessmentResource() .build(); Long assessmentId = 1L; when(assessmentRestService.getById(assessmentId)).thenReturn(restSuccess(expected)); assertSame(expected, service.getById(assessmentId)); verify(assessmentRestService, only()).getById(assessmentId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public AssessmentResource getAssignableById(Long id) { return assessmentRestService.getAssignableById(id).getSuccess(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void getAssignableById() throws Exception { AssessmentResource expected = newAssessmentResource().build(); Long assessmentId = 1L; when(assessmentRestService.getAssignableById(assessmentId)).thenReturn(restSuccess(expected)); assertSame(expected, service.getAssignableById(assessmentId)); verify(assessmentRestService, only()).getAssignableById(assessmentId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public AssessmentResource getRejectableById(Long id) { return assessmentRestService.getRejectableById(id).getSuccess(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void getRejectableById() throws Exception { AssessmentResource expected = newAssessmentResource().build(); Long assessmentId = 1L; when(assessmentRestService.getRejectableById(assessmentId)).thenReturn(restSuccess(expected)); assertSame(expected, service.getRejectableById(assessmentId)); verify(assessmentRestService, only()).getRejectableById(assessmentId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId) { return assessmentRestService.getByUserAndCompetition(userId, competitionId).getSuccess(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void getByUserAndCompetition() throws Exception { List<AssessmentResource> expected = newAssessmentResource().build(2); Long userId = 1L; Long competitionId = 2L; when(assessmentRestService.getByUserAndCompetition(userId, competitionId)).thenReturn(restSuccess(expected)); assertSame(expected, service.getByUserAndCompetition(userId, competitionId)); verify(assessmentRestService, only()).getByUserAndCompetition(userId, competitionId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public AssessmentTotalScoreResource getTotalScore(Long assessmentId) { return assessmentRestService.getTotalScore(assessmentId).getSuccess(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void getTotalScore() throws Exception { AssessmentTotalScoreResource expected = newAssessmentTotalScoreResource().build(); Long assessmentId = 1L; when(assessmentRestService.getTotalScore(assessmentId)).thenReturn(restSuccess(expected)); assertSame(expected, service.getTotalScore(assessmentId)); verify(assessmentRestService, only()).getTotalScore(assessmentId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment) { return assessmentRestService.recommend(assessmentId, new AssessmentFundingDecisionOutcomeResourceBuilder() .setFundingConfirmation(fundingConfirmation) .setFeedback(feedback) .setComment(comment) .createAssessmentFundingDecisionResource()).toServiceResult(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void recommend() throws Exception { Long assessmentId = 1L; String feedback = "feedback for decision"; String comment = "comment for decision"; AssessmentFundingDecisionOutcomeResource assessmentFundingDecisionOutcomeResource = newAssessmentFundingDecisionOutcomeResource() .withFundingConfirmation(TRUE) .withFeedback(feedback) .withComment(comment) .build(); when(assessmentRestService.recommend(assessmentId, assessmentFundingDecisionOutcomeResource)).thenReturn(restSuccess()); ServiceResult<Void> response = service.recommend(assessmentId, TRUE, feedback, comment); assertTrue(response.isSuccess()); verify(assessmentRestService, only()).recommend(assessmentId, assessmentFundingDecisionOutcomeResource); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment) { AssessmentRejectOutcomeResource assessmentRejectOutcomeResource = new AssessmentRejectOutcomeResource(); assessmentRejectOutcomeResource.setRejectReason(reason); assessmentRejectOutcomeResource.setRejectComment(comment); return assessmentRestService.rejectInvitation(assessmentId, assessmentRejectOutcomeResource).toServiceResult(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void rejectInvitation() throws Exception { Long assessmentId = 1L; AssessmentRejectOutcomeValue reason = CONFLICT_OF_INTEREST; String comment = "comment for rejection"; AssessmentRejectOutcomeResource assessmentRejectOutcomeResource = newAssessmentRejectOutcomeResource() .withRejectReason(reason) .withRejectComment(comment) .build(); when(assessmentRestService.rejectInvitation(assessmentId, assessmentRejectOutcomeResource)).thenReturn(restSuccess()); ServiceResult<Void> response = service.rejectInvitation(assessmentId, reason, comment); assertTrue(response.isSuccess()); verify(assessmentRestService, only()).rejectInvitation(assessmentId, assessmentRejectOutcomeResource); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public ServiceResult<Void> acceptInvitation(Long assessmentId) { return assessmentRestService.acceptInvitation(assessmentId).toServiceResult(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void acceptInvitation() throws Exception { Long assessmentId = 1L; when(assessmentRestService.acceptInvitation(assessmentId)).thenReturn(restSuccess()); ServiceResult<Void> response = service.acceptInvitation(assessmentId); assertTrue(response.isSuccess()); verify(assessmentRestService, only()).acceptInvitation(assessmentId); }
### Question: AssessmentServiceImpl implements AssessmentService { @Override public ServiceResult<Void> submitAssessments(List<Long> assessmentIds) { AssessmentSubmissionsResource assessmentSubmissions = new AssessmentSubmissionsResource(); assessmentSubmissions.setAssessmentIds(assessmentIds); return assessmentRestService.submitAssessments(assessmentSubmissions).toServiceResult(); } @Override AssessmentResource getById(Long id); @Override AssessmentResource getAssignableById(Long id); @Override AssessmentResource getRejectableById(Long id); @Override List<AssessmentResource> getByUserAndCompetition(Long userId, Long competitionId); @Override AssessmentTotalScoreResource getTotalScore(Long assessmentId); @Override ServiceResult<Void> recommend(Long assessmentId, Boolean fundingConfirmation, String feedback, String comment); @Override ServiceResult<Void> rejectInvitation(Long assessmentId, AssessmentRejectOutcomeValue reason, String comment); @Override ServiceResult<Void> acceptInvitation(Long assessmentId); @Override ServiceResult<Void> submitAssessments(List<Long> assessmentIds); }### Answer: @Test public void submitAssessments() throws Exception { AssessmentSubmissionsResource assessmentSubmissions = newAssessmentSubmissionsResource() .withAssessmentIds(asList(1L, 2L)) .build(); when(assessmentRestService.submitAssessments(assessmentSubmissions)).thenReturn(restSuccess()); ServiceResult<Void> response = service.submitAssessments(asList(1L, 2L)); assertTrue(response.isSuccess()); verify(assessmentRestService, only()).submitAssessments(assessmentSubmissions); }
### Question: AssessmentFeedbackApplicationDetailsViewModel extends BaseAssessmentFeedbackViewModel { public boolean isKtpCompetition() { return ktpCompetition; } AssessmentFeedbackApplicationDetailsViewModel(long applicationId, String applicationName, LocalDate applicationStartDate, long applicationDurationInMonths, long daysLeft, long daysLeftPercentage, String questionShortName, boolean ktpCompetition); long getApplicationId(); String getApplicationName(); LocalDate getApplicationStartDate(); long getApplicationDurationInMonths(); long getDaysLeft(); long getDaysLeftPercentage(); String getQuestionShortName(); boolean isKtpCompetition(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test public void testKtpCompetition() { long applicationId = 1L; long applicationDurationInMonths = 15L; long daysLeft = 10L; long daysLeftPercentage = 5L; CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.KTP).build(); AssessmentFeedbackApplicationDetailsViewModel viewModel = new AssessmentFeedbackApplicationDetailsViewModel(applicationId, null, null, applicationDurationInMonths, daysLeft, daysLeftPercentage, null, competitionResource.isKtp()); assertTrue(viewModel.isKtpCompetition()); } @Test public void testNonKtpCompetition() { long applicationId = 1L; long applicationDurationInMonths = 15L; long daysLeft = 10L; long daysLeftPercentage = 5L; CompetitionResource competitionResource = CompetitionResourceBuilder.newCompetitionResource() .withFundingType(FundingType.GRANT).build(); AssessmentFeedbackApplicationDetailsViewModel viewModel = new AssessmentFeedbackApplicationDetailsViewModel(applicationId, null, null, applicationDurationInMonths, daysLeft, daysLeftPercentage, null, competitionResource.isKtp()); assertFalse(viewModel.isKtpCompetition()); }
### Question: AssessorServiceImpl implements AssessorService { @Override public ServiceResult<Void> createAssessorByInviteHash(String inviteHash, RegistrationForm registrationForm, AddressResource address) { UserRegistrationResource userRegistrationResource = new UserRegistrationResource(); userRegistrationResource.setFirstName(registrationForm.getFirstName()); userRegistrationResource.setLastName(registrationForm.getLastName()); userRegistrationResource.setPhoneNumber(registrationForm.getPhoneNumber()); userRegistrationResource.setPassword(registrationForm.getPassword()); userRegistrationResource.setAddress(address); return assessorRestService.createAssessorByInviteHash(inviteHash, userRegistrationResource).toServiceResult(); } @Override ServiceResult<Void> createAssessorByInviteHash(String inviteHash, RegistrationForm registrationForm, AddressResource address); }### Answer: @Test public void createAssessorByInviteHash() { String hash = "hash"; String firstName = "Felix"; String lastName = "Wilson"; String phoneNumber = "12345678"; String password = "password"; RegistrationForm form = new RegistrationForm(); form.setFirstName(firstName); form.setLastName(lastName); form.setPhoneNumber(phoneNumber); form.setPassword(password); AddressResource addressResource = newAddressResource().build(); UserRegistrationResource userRegistration = newUserRegistrationResource() .withFirstName(firstName) .withLastName(lastName) .withPhoneNumber(phoneNumber) .withPassword(password) .withAddress(addressResource) .build(); when(assessorRestService.createAssessorByInviteHash(hash, userRegistration)).thenReturn(restSuccess()); ServiceResult<Void> response = service.createAssessorByInviteHash(hash, form, addressResource); assertTrue(response.isSuccess()); verify(assessorRestService, only()).createAssessorByInviteHash(hash, userRegistration); }
### Question: AssessmentReviewApplicationSummaryController { @GetMapping("/application/{applicationId}") public String viewApplication(@PathVariable("applicationId") long applicationId, @PathVariable("reviewId") long reviewId, Model model, UserResource user) { model.addAttribute("model", assessmentReviewApplicationSummaryModelPopulator.populateModel(user, applicationId)); return "assessor-panel-application-overview"; } @GetMapping("/application/{applicationId}") String viewApplication(@PathVariable("applicationId") long applicationId, @PathVariable("reviewId") long reviewId, Model model, UserResource user); }### Answer: @Test public void viewApplication() throws Exception { long reviewId = 1L; long applicationId = 2L; AssessmentReviewApplicationSummaryViewModel model = mock(AssessmentReviewApplicationSummaryViewModel.class); when(assessmentReviewApplicationSummaryModelPopulator.populateModel(getLoggedInUser(), applicationId)).thenReturn(model); mockMvc.perform(get("/review/{reviewId}/application/{applicationId}", reviewId, applicationId)) .andExpect(view().name("assessor-panel-application-overview")) .andExpect(model().attribute("model", model)); }
### Question: CompetitionInviteViewModel extends BaseInviteViewModel { public Boolean isKtpCompetition() { return KTP.equals(competitionFundingType); } CompetitionInviteViewModel(String competitionInviteHash, CompetitionInviteResource invite, boolean userLoggedIn); String getCompetitionInviteHash(); ZonedDateTime getAcceptsDate(); ZonedDateTime getDeadlineDate(); ZonedDateTime getBriefingDate(); BigDecimal getAssessorPay(); Boolean isKtpCompetition(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testNonKtpCompetition() { String inviteHash = "invite-hash"; CompetitionInviteResource competitionInviteResource = CompetitionInviteResourceBuilder.newCompetitionInviteResource() .withCompetitionFundingType(FundingType.GRANT) .build(); CompetitionInviteViewModel viewModel = new CompetitionInviteViewModel(inviteHash, competitionInviteResource, false); assertFalse(viewModel.isKtpCompetition()); } @Test public void testKtpCompetition() { String inviteHash = "invite-hash"; CompetitionInviteResource competitionInviteResource = CompetitionInviteResourceBuilder.newCompetitionInviteResource() .withCompetitionFundingType(FundingType.KTP) .build(); CompetitionInviteViewModel viewModel = new CompetitionInviteViewModel(inviteHash, competitionInviteResource, false); assertTrue(viewModel.isKtpCompetition()); }
### Question: ReviewInviteController { @GetMapping("/invite-accept/panel/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") public String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash) { inviteRestService.acceptInvite(inviteHash).getSuccess(); return "redirect:/assessor/dashboard"; } @GetMapping("/invite/panel/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) ReviewInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/panel/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") ReviewInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/panel/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/panel/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void confirmAcceptInvite() throws Exception { when(reviewInviteRestService.acceptInvite("hash")).thenReturn(restSuccess()); mockMvc.perform(get("/invite-accept/panel/{inviteHash}/accept", "hash")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/assessor/dashboard")); verify(reviewInviteRestService).acceptInvite("hash"); }
### Question: ReviewInviteController { @GetMapping("/invite/panel/{inviteHash}/reject/thank-you") public String rejectThankYou(@PathVariable("inviteHash") String inviteHash) { return "assessor-panel-reject"; } @GetMapping("/invite/panel/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) ReviewInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/panel/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") ReviewInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/panel/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/panel/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void rejectThankYou() throws Exception { mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash")) .andExpect(status().isOk()) .andExpect(view().name("assessor-panel-reject")) .andReturn(); }
### Question: InterviewInviteController { @GetMapping("/invite-accept/interview/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") public String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash) { inviteRestService.acceptInvite(inviteHash).getSuccess(); return "redirect:/assessor/dashboard"; } @GetMapping("/invite/interview/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) InterviewInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/interview/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") InterviewInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/interview/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/interview/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void confirmAcceptInvite() throws Exception { when(interviewInviteRestService.acceptInvite("hash")).thenReturn(restSuccess()); mockMvc.perform(get("/invite-accept/interview/{inviteHash}/accept", "hash")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/assessor/dashboard")); verify(interviewInviteRestService).acceptInvite("hash"); }
### Question: InterviewInviteController { @GetMapping("/invite/interview/{inviteHash}/reject/thank-you") public String rejectThankYou(@PathVariable("inviteHash") String inviteHash) { return "assessor-interview-reject"; } @GetMapping("/invite/interview/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) InterviewInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/interview/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") InterviewInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/interview/{inviteHash}/accept") @SecuredBySpring(value = "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/interview/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void rejectThankYou() throws Exception { mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash")) .andExpect(status().isOk()) .andExpect(view().name("assessor-interview-reject")) .andReturn(); }
### Question: CompetitionInviteController { @GetMapping("/invite-accept/competition/{inviteHash}/accept") @SecuredBySpring(value= "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") public String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash) { inviteRestService.acceptInvite(inviteHash).getSuccess(); return "redirect:/assessor/dashboard"; } @GetMapping("/invite/competition/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) CompetitionInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/competition/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") CompetitionInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/competition/{inviteHash}/accept") @SecuredBySpring(value= "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/competition/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void confirmAcceptInvite() throws Exception { when(competitionInviteRestService.acceptInvite("hash")).thenReturn(restSuccess()); mockMvc.perform(get("/invite-accept/competition/{inviteHash}/accept", "hash")) .andExpect(status().is3xxRedirection()) .andExpect(redirectedUrl("/assessor/dashboard")); verify(competitionInviteRestService).acceptInvite("hash"); }
### Question: FileFunctions { public static final File pathElementsToFile(List<String> pathElements) { return new File(pathElementsToPathString(pathElements)); } private FileFunctions(); static final String pathElementsToPathString(List<String> pathElements); static final List<String> pathStringToPathElements(final String pathString); static final String pathElementsToAbsolutePathString(List<String> pathElements, String absolutePathPrefix); static final List<String> pathElementsToAbsolutePathElements(List<String> pathElements, String absolutePathPrefix); static final File pathElementsToFile(List<String> pathElements); static final Path pathElementsToPath(List<String> pathElements); }### Answer: @Test public void testPathElementsToFile() { assertEquals("path" + separator + "to" + separator + "file", FileFunctions.pathElementsToFile(asList("path", "to", "file")).getPath()); } @Test public void testPathElementsToFileWithLeadingSeparator() { assertEquals(separator + "path" + separator + "to" + separator + "file", FileFunctions.pathElementsToFile(asList(separator + "path", "to", "file")).getPath()); } @Test public void testPathElementsToFileWithEmptyStringList() { assertEquals("", FileFunctions.pathElementsToFile(asList()).getPath()); } @Test public void testPathElementsToFileWithNullStringList() { assertEquals("", FileFunctions.pathElementsToFile(null).getPath()); } @Test public void testPathElementsToFileWithNullStringElements() { assertEquals("path" + separator + "null" + separator + "file", FileFunctions.pathElementsToFile(asList("path", null, "file")).getPath()); }
### Question: CompetitionInviteController { @GetMapping("/invite/competition/{inviteHash}/reject/thank-you") public String rejectThankYou(@PathVariable("inviteHash") String inviteHash) { return "assessor-competition-reject"; } @GetMapping("/invite/competition/{inviteHash}") String openInvite(@PathVariable("inviteHash") String inviteHash, @ModelAttribute(name = "form", binding = false) CompetitionInviteForm form, UserResource loggedInUser, Model model); @PostMapping("/invite/competition/{inviteHash}/decision") String handleDecision(Model model, @PathVariable("inviteHash") String inviteHash, UserResource loggedInUser, @Valid @ModelAttribute("form") CompetitionInviteForm form, BindingResult bindingResult, ValidationHandler validationHandler); @GetMapping("/invite-accept/competition/{inviteHash}/accept") @SecuredBySpring(value= "TODO", description = "TODO") @PreAuthorize("hasAuthority('assessor')") String confirmAcceptInvite(@PathVariable("inviteHash") String inviteHash); @GetMapping("/invite/competition/{inviteHash}/reject/thank-you") String rejectThankYou(@PathVariable("inviteHash") String inviteHash); @ModelAttribute("rejectionReasons") List<RejectionReasonResource> populateRejectionReasons(); }### Answer: @Test public void rejectThankYou() throws Exception { mockMvc.perform(get(restUrl + "{inviteHash}/reject/thank-you", "hash")) .andExpect(status().isOk()) .andExpect(view().name("assessor-competition-reject")) .andReturn(); }
### Question: FormInputResponseServiceImpl implements FormInputResponseService { @Override public Map<Long, FormInputResponseResource> mapFormInputResponsesToFormInput(List<FormInputResponseResource> responses) { return simpleToMap( responses, response -> response.getFormInput(), response -> response ); } @Override Map<Long, FormInputResponseResource> mapFormInputResponsesToFormInput(List<FormInputResponseResource> responses); }### Answer: @Test public void mapResponsesToFormInputs() { List<FormInputResponseResource> formInputResponses = newFormInputResponseResource(). withFormInputs(3L, 2L, 1L). build(3); Map<Long, FormInputResponseResource> response = service.mapFormInputResponsesToFormInput(formInputResponses); assertEquals(formInputResponses.get(0), response.get(3L)); assertEquals(formInputResponses.get(1), response.get(2L)); assertEquals(formInputResponses.get(2), response.get(1L)); }
### Question: GrantAgreementReadOnlyPopulator implements QuestionReadOnlyViewModelPopulator<GrantAgreementReadOnlyViewModel> { @Override public GrantAgreementReadOnlyViewModel populate(CompetitionResource competition, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) { Optional<FileEntryResource> grantAgreement = grantTransferRestService.findGrantAgreement(data.getApplication().getId()).getOptionalSuccessObject(); return new GrantAgreementReadOnlyViewModel(data, question, grantAgreement.map(FileEntryResource::getName).orElse(null)); } GrantAgreementReadOnlyPopulator(EuGrantTransferRestService grantTransferRestService); @Override GrantAgreementReadOnlyViewModel populate(CompetitionResource competition, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings); @Override Set<QuestionSetupType> questionTypes(); }### Answer: @Test public void populate() { ApplicationResource application = newApplicationResource() .build(); CompetitionResource competition = newCompetitionResource() .build(); QuestionResource question = newQuestionResource() .withShortName("Grant agreement") .build(); FileEntryResource file = newFileEntryResource().withName("file.name").build(); when(euGrantTransferRestService.findGrantAgreement(application.getId())).thenReturn(restSuccess(file)); ApplicationReadOnlyData data = new ApplicationReadOnlyData(application, competition, newUserResource().build(), emptyList(), emptyList(), emptyList(), emptyList(), emptyList(), emptyList()); GrantAgreementReadOnlyViewModel viewModel = populator.populate(competition, question, data, defaultSettings()); assertEquals("file.name", viewModel.getFilename()); assertEquals("Grant agreement", viewModel.getName()); assertEquals(application.getId(), (Long) viewModel.getApplicationId()); assertEquals(question.getId(), (Long) viewModel.getQuestionId()); assertFalse(viewModel.isComplete()); assertFalse(viewModel.isLead()); }
### Question: ResearchCategoryReadOnlyViewModelPopulator implements QuestionReadOnlyViewModelPopulator<ResearchCategoryReadOnlyViewModel> { @Override public ResearchCategoryReadOnlyViewModel populate(CompetitionResource competition, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings) { return new ResearchCategoryReadOnlyViewModel(data, question); } @Override ResearchCategoryReadOnlyViewModel populate(CompetitionResource competition, QuestionResource question, ApplicationReadOnlyData data, ApplicationReadOnlySettings settings); @Override Set<QuestionSetupType> questionTypes(); }### Answer: @Test public void populate() { ApplicationResource application = newApplicationResource() .withResearchCategory(newResearchCategoryResource().withName("Research category").build()) .build(); CompetitionResource competition = newCompetitionResource() .build(); QuestionResource question = newQuestionResource() .withShortName("Research category") .build(); ApplicationReadOnlyData data = new ApplicationReadOnlyData(application, competition, newUserResource().build(), emptyList(), emptyList(), emptyList(), emptyList(), emptyList(), emptyList()); ResearchCategoryReadOnlyViewModel viewModel = populator.populate(competition, question, data, defaultSettings()); assertEquals("Research category", viewModel.getResearchCategory()); assertEquals("Research category", viewModel.getName()); assertEquals(application.getId(), (Long) viewModel.getApplicationId()); assertEquals(question.getId(), (Long) viewModel.getQuestionId()); assertFalse(viewModel.isComplete()); assertFalse(viewModel.isLead()); }
### Question: ApplicationCompletedViewModel { public boolean completedOrMarkedAsComplete(QuestionResource questionResource, SectionResource sectionResource) throws ExecutionException, InterruptedException { return (questionResource.isMarkAsCompletedEnabled() && getMarkedAsComplete().contains(questionResource.getId())) || completedSectionsByUserOrganisation.contains(sectionResource.getId()); } ApplicationCompletedViewModel(Set<Long> sectionsMarkedAsComplete, Future<Set<Long>> markedAsComplete, Set<Long> completedSectionsByUserOrganisation, boolean financeSectionComplete, boolean financeOverviewSectionComplete); Set<Long> getSectionsMarkedAsComplete(); Set<Long> getMarkedAsComplete(); boolean completedOrMarkedAsComplete(QuestionResource questionResource, SectionResource sectionResource); boolean isFinanceSectionComplete(); boolean isFinanceOverviewSectionComplete(); }### Answer: @Test public void completedOrMarkedAsCompleteTest() throws Exception{ QuestionResource questionResource = newQuestionResource() .with(questionResource1 -> { questionResource1.setId(1L); questionResource1.setMarkAsCompletedEnabled(Boolean.TRUE); }) .build(); SectionResource sectionResource = newSectionResource().withId(54L).build(); assertTrue(viewModel.completedOrMarkedAsComplete(questionResource, sectionResource)); questionResource = newQuestionResource() .with(questionResource1 -> { questionResource1.setId(23L); questionResource1.setMarkAsCompletedEnabled(Boolean.TRUE); }) .build(); assertFalse(viewModel.completedOrMarkedAsComplete(questionResource, sectionResource)); questionResource = newQuestionResource() .with(questionResource1 -> { questionResource1.setId(3L); questionResource1.setMarkAsCompletedEnabled(Boolean.FALSE); }) .build(); assertFalse(viewModel.completedOrMarkedAsComplete(questionResource, sectionResource)); sectionResource = newSectionResource().withId(1L).build(); assertTrue(viewModel.completedOrMarkedAsComplete(questionResource, sectionResource)); }
### Question: NavigationViewModel { public Boolean getHasNavigation(){ return !StringUtils.isEmpty(previousUrl) || !StringUtils.isEmpty(nextUrl); } String getPreviousUrl(); void setPreviousUrl(String previousUrl); String getPreviousText(); void setPreviousText(String previousText); String getNextUrl(); void setNextUrl(String nextUrl); String getNextText(); void setNextText(String nextText); Boolean getHasNavigation(); @Override boolean equals(Object o); @Override int hashCode(); }### Answer: @Test public void testGetHasNavigation() { viewModel.setNextText("Next one please"); viewModel.setNextUrl("http: assertEquals(Boolean.TRUE, viewModel.getHasNavigation()); } @Test public void testGetHasNavigationFalse() { assertEquals(Boolean.FALSE, viewModel.getHasNavigation()); }
### Question: SpendProfileCalculations { BigDecimal getOverheadPercentage() { BigDecimal total = getTotal(); if (total.compareTo(BigDecimal.ZERO) == 0) { return BigDecimal.ZERO; } return getTotalOverhead().multiply(BigDecimal.valueOf(100)) .divide(total, 2, BigDecimal.ROUND_HALF_UP); } SpendProfileCalculations(SpendProfile spendProfile); }### Answer: @Test public void overheadCalculationZero() { List<Cost> costs = asList( newOverheadCost(BigDecimal.ZERO), newLabourCost(BigDecimal.ZERO) ); assertThat(BigDecimal.ZERO, Matchers.comparesEqualTo(newCalculations(costs).getOverheadPercentage())); } @Test public void overheadCalculationFifty() { List<Cost> costs = asList( newOverheadCost(BigDecimal.ONE), newLabourCost(BigDecimal.ONE) ); assertThat(FIFTY_PERCENT, Matchers.comparesEqualTo(newCalculations(costs).getOverheadPercentage())); } @Test public void overheadCalculationHundred() { List<Cost> costs = asList( newOverheadCost(BigDecimal.ONE), newLabourCost(BigDecimal.ZERO) ); assertThat(HUNDRED_PERCENT, Matchers.comparesEqualTo(newCalculations(costs).getOverheadPercentage())); }
### Question: SectionServiceImpl implements SectionService { @Override public List<SectionResource> getSectionsForCompetitionByType(long competitionId, SectionType type) { return sectionRestService.getSectionsByCompetitionIdAndType(competitionId, type).getSuccess(); } @Override ValidationMessages markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override void markAsNotRequired(Long sectionId, Long applicationId, Long markedAsCompleteById); @Override void markAsInComplete(Long sectionId, Long applicationId, Long markedAsInCompleteById); @Override SectionResource getById(Long sectionId); @Override List<Long> getCompleted(Long applicationId, Long organisationId); @Override Map<Long, Set<Long>> getCompletedSectionsByOrganisation(Long applicationId); @Override List<SectionResource> filterParentSections(List<SectionResource> sections); @Override List<SectionResource> getAllByCompetitionId(final long competitionId); List<SectionResource> findResourceByIdInList(final List<Long> ids, final List<SectionResource> list); @Override SectionResource getSectionByQuestionId(long questionId); @Override Set<Long> getQuestionsForSectionAndSubsections(long sectionId); @Override List<SectionResource> getSectionsForCompetitionByType(long competitionId, SectionType type); @Override SectionResource getFinanceSection(long competitionId); @Override SectionResource getTermsAndConditionsSection(long competitionId); @Override SectionResource getOrganisationFinanceSection(long competitionId); }### Answer: @Test public void getSectionsByType() { SectionResource section = newSectionResource().build(); when(sectionRestService.getSectionsByCompetitionIdAndType(competition.getId(), SectionType.FINANCE)).thenReturn(restSuccess(singletonList(section))); List<SectionResource> result = service.getSectionsForCompetitionByType(competition.getId(), SectionType.FINANCE); assertEquals(1, result.size()); assertEquals(section, result.get(0)); }
### Question: SectionServiceImpl implements SectionService { @Override public SectionResource getFinanceSection(long competitionId) { return getSingleSectionByType(competitionId, SectionType.FINANCE); } @Override ValidationMessages markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override void markAsNotRequired(Long sectionId, Long applicationId, Long markedAsCompleteById); @Override void markAsInComplete(Long sectionId, Long applicationId, Long markedAsInCompleteById); @Override SectionResource getById(Long sectionId); @Override List<Long> getCompleted(Long applicationId, Long organisationId); @Override Map<Long, Set<Long>> getCompletedSectionsByOrganisation(Long applicationId); @Override List<SectionResource> filterParentSections(List<SectionResource> sections); @Override List<SectionResource> getAllByCompetitionId(final long competitionId); List<SectionResource> findResourceByIdInList(final List<Long> ids, final List<SectionResource> list); @Override SectionResource getSectionByQuestionId(long questionId); @Override Set<Long> getQuestionsForSectionAndSubsections(long sectionId); @Override List<SectionResource> getSectionsForCompetitionByType(long competitionId, SectionType type); @Override SectionResource getFinanceSection(long competitionId); @Override SectionResource getTermsAndConditionsSection(long competitionId); @Override SectionResource getOrganisationFinanceSection(long competitionId); }### Answer: @Test public void getFinanceSection() { SectionResource section = newSectionResource().build(); when(sectionRestService.getSectionsByCompetitionIdAndType(competition.getId(), SectionType.FINANCE)).thenReturn(restSuccess(singletonList(section))); SectionResource result = service.getFinanceSection(competition.getId()); assertEquals(section, result); }
### Question: SectionServiceImpl implements SectionService { @Override public SectionResource getOrganisationFinanceSection(long competitionId) { return getSingleSectionByType(competitionId, ORGANISATION_FINANCES); } @Override ValidationMessages markAsComplete(long sectionId, long applicationId, long markedAsCompleteById); @Override void markAsNotRequired(Long sectionId, Long applicationId, Long markedAsCompleteById); @Override void markAsInComplete(Long sectionId, Long applicationId, Long markedAsInCompleteById); @Override SectionResource getById(Long sectionId); @Override List<Long> getCompleted(Long applicationId, Long organisationId); @Override Map<Long, Set<Long>> getCompletedSectionsByOrganisation(Long applicationId); @Override List<SectionResource> filterParentSections(List<SectionResource> sections); @Override List<SectionResource> getAllByCompetitionId(final long competitionId); List<SectionResource> findResourceByIdInList(final List<Long> ids, final List<SectionResource> list); @Override SectionResource getSectionByQuestionId(long questionId); @Override Set<Long> getQuestionsForSectionAndSubsections(long sectionId); @Override List<SectionResource> getSectionsForCompetitionByType(long competitionId, SectionType type); @Override SectionResource getFinanceSection(long competitionId); @Override SectionResource getTermsAndConditionsSection(long competitionId); @Override SectionResource getOrganisationFinanceSection(long competitionId); }### Answer: @Test public void getOrganisationFinanceSection() { SectionResource section = newSectionResource().build(); when(sectionRestService.getSectionsByCompetitionIdAndType(competition.getId(), SectionType.ORGANISATION_FINANCES)).thenReturn(restSuccess(singletonList(section))); SectionResource result = service.getOrganisationFinanceSection(competition.getId()); assertEquals(section, result); }
### Question: ApplicationServiceImpl implements ApplicationService { @Override public ApplicationResource getById(Long applicationId) { if (applicationId == null) { return null; } return applicationRestService.getApplicationById(applicationId).getSuccess(); } @Override ApplicationResource getById(Long applicationId); @Override ApplicationResource createApplication(long competitionId, long userId, long organisationId, String applicationName); @Override ServiceResult<ValidationMessages> save(ApplicationResource application); @Override OrganisationResource getLeadOrganisation(Long applicationId); @Override ServiceResult<Void> removeCollaborator(Long applicationInviteId); @Override ServiceResult<Void> markAsIneligible(long applicationId, IneligibleOutcomeResource reason); }### Answer: @Test public void getById() { Long applicationId = 3L; ApplicationResource application = new ApplicationResource(); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); ApplicationResource returnedApplication = service.getById(applicationId); assertEquals(application, returnedApplication); } @Test(expected = ObjectNotFoundException.class) public void testGetByIdNotFound() { Long applicationId = 5L; when(applicationRestService.getApplicationById(applicationId)).thenThrow(new ObjectNotFoundException("Application not found", asList(applicationId))); service.getById(applicationId); } @Test public void getByIdNullValue() { ApplicationResource returnedApplication = service.getById(null); assertEquals(null, returnedApplication); }
### Question: GrantProcessServiceImpl implements GrantProcessService { @Override @Transactional(readOnly = true) public List<GrantProcess> findReadyToSend() { return grantProcessRepository.findByPendingIsTrue(); } @Override @Transactional(readOnly = true) Optional<GrantProcess> findByApplicationId(Long applicationId); @Override void createGrantProcess(long applicationId); @Override @Transactional(readOnly = true) List<GrantProcess> findReadyToSend(); @Override @Transactional(readOnly = true) Optional<GrantProcess> findOneReadyToSend(); @Override void sendSucceeded(long applicationId); @Override void sendFailed(long applicationId, String message); }### Answer: @Test public void findReadyToSend() { GrantProcess grantProcessOne = new GrantProcess(1); GrantProcess grantProcessTwo = new GrantProcess(2); List<GrantProcess> readyToSend = asList(grantProcessOne, grantProcessTwo); when(grantProcessRepository.findByPendingIsTrue()).thenReturn(readyToSend); assertThat(service.findReadyToSend(), is(readyToSend)); verify(grantProcessRepository, only()).findByPendingIsTrue(); }
### Question: ApplicationServiceImpl implements ApplicationService { @Override public ServiceResult<ValidationMessages> save(ApplicationResource application) { return applicationRestService.saveApplication(application).toServiceResult(); } @Override ApplicationResource getById(Long applicationId); @Override ApplicationResource createApplication(long competitionId, long userId, long organisationId, String applicationName); @Override ServiceResult<ValidationMessages> save(ApplicationResource application); @Override OrganisationResource getLeadOrganisation(Long applicationId); @Override ServiceResult<Void> removeCollaborator(Long applicationInviteId); @Override ServiceResult<Void> markAsIneligible(long applicationId, IneligibleOutcomeResource reason); }### Answer: @Test public void save() { ApplicationResource application = new ApplicationResource(); ValidationMessages validationMessages = new ValidationMessages(); when(applicationRestService.saveApplication(application)).thenReturn(restSuccess(validationMessages)); ServiceResult<ValidationMessages> result = service.save(application); assertTrue(result.isSuccess()); Mockito.inOrder(applicationRestService).verify(applicationRestService, calls(1)).saveApplication(application); }
### Question: ApplicationServiceImpl implements ApplicationService { @Override public ServiceResult<Void> removeCollaborator(Long applicationInviteId) { return inviteRestService.removeApplicationInvite(applicationInviteId).toServiceResult(); } @Override ApplicationResource getById(Long applicationId); @Override ApplicationResource createApplication(long competitionId, long userId, long organisationId, String applicationName); @Override ServiceResult<ValidationMessages> save(ApplicationResource application); @Override OrganisationResource getLeadOrganisation(Long applicationId); @Override ServiceResult<Void> removeCollaborator(Long applicationInviteId); @Override ServiceResult<Void> markAsIneligible(long applicationId, IneligibleOutcomeResource reason); }### Answer: @Test public void removeCollaborator() { Long applicationInviteId = 80512L; ServiceResult<Void> result = service.removeCollaborator(applicationInviteId); assertTrue(result.isSuccess()); Mockito.inOrder(inviteRestService).verify(inviteRestService, calls(1)).removeApplicationInvite(applicationInviteId); }
### Question: ApplicationServiceImpl implements ApplicationService { @Override public ServiceResult<Void> markAsIneligible(long applicationId, IneligibleOutcomeResource reason) { return applicationRestService.markAsIneligible(applicationId, reason).toServiceResult(); } @Override ApplicationResource getById(Long applicationId); @Override ApplicationResource createApplication(long competitionId, long userId, long organisationId, String applicationName); @Override ServiceResult<ValidationMessages> save(ApplicationResource application); @Override OrganisationResource getLeadOrganisation(Long applicationId); @Override ServiceResult<Void> removeCollaborator(Long applicationInviteId); @Override ServiceResult<Void> markAsIneligible(long applicationId, IneligibleOutcomeResource reason); }### Answer: @Test public void markAsIneligible() { long applicationId = 1L; IneligibleOutcomeResource reason = newIneligibleOutcomeResource() .withReason("reason") .build(); when(applicationRestService.markAsIneligible(applicationId, reason)).thenReturn(restSuccess()); ServiceResult<Void> result = service.markAsIneligible(applicationId, reason); assertTrue(result.isSuccess()); InOrder inOrder = inOrder(applicationRestService); inOrder.verify(applicationRestService).markAsIneligible(applicationId, reason); inOrder.verifyNoMoreInteractions(); }
### Question: ApplicationPrintPopulator { public String print(final Long applicationId, Model model, UserResource user) { ApplicationResource application = applicationRestService.getApplicationById(applicationId).getSuccess(); CompetitionResource competition = competitionRestService.getCompetitionById(application.getCompetition()).getSuccess(); ApplicationReadOnlySettings settings = defaultSettings() .setIncludeAllAssessorFeedback(userCanViewFeedback(user, competition, application)); ApplicationReadOnlyViewModel applicationReadOnlyViewModel = applicationReadOnlyViewModelPopulator.populate(applicationId, user, settings); model.addAttribute("model", applicationReadOnlyViewModel); return "application/print"; } String print(final Long applicationId, Model model, UserResource user); }### Answer: @Test public void testPrint() { Model model = mock(Model.class); UserResource user = UserResourceBuilder.newUserResource().build(); long applicationId = 1L; ApplicationReadOnlyViewModel viewModel = mock(ApplicationReadOnlyViewModel.class); CompetitionResource competition = newCompetitionResource().build(); ApplicationResource application = newApplicationResource() .withId(applicationId) .withCompetition(competition.getId()) .build(); when(applicationRestService.getApplicationById(applicationId)).thenReturn(restSuccess(application)); when(competitionRestService.getCompetitionById(competition.getId())).thenReturn(restSuccess(competition)); when(applicationReadOnlyViewModelPopulator.populate(applicationId, user, defaultSettings().setIncludeAllAssessorFeedback(true))).thenReturn(viewModel); applicationPrintPopulator.print(applicationId, model, user); verify(model).addAttribute("model", viewModel); }
### Question: FinanceServiceImpl implements FinanceService { @Override public ApplicationFinanceResource getApplicationFinanceByApplicationIdAndOrganisationId(Long applicationId, Long organisationId) { return applicationFinanceRestService.getApplicationFinance(applicationId, organisationId).getSuccess(); } @Override ApplicationFinanceResource getApplicationFinance(Long userId, Long applicationId); @Override ApplicationFinanceResource getApplicationFinanceByApplicationIdAndOrganisationId(Long applicationId, Long organisationId); @Override ApplicationFinanceResource getApplicationFinanceDetails(Long userId, Long applicationId); @Override ApplicationFinanceResource getApplicationFinanceDetails(Long userId, Long applicationId, Long organisationId); @Override List<ApplicationFinanceResource> getApplicationFinanceDetails(Long applicationId); @Override List<ApplicationFinanceResource> getApplicationFinanceTotals(Long applicationId); @Override RestResult<FileEntryResource> getFinanceEntry(Long applicationFinanceFileEntryId); @Override RestResult<FileEntryResource> getFinanceEntryByApplicationFinanceId(Long applicationFinanceId); @Override RestResult<ByteArrayResource> getFinanceDocumentByApplicationFinance(Long applicationFinanceId); }### Answer: @Test public void testGetApplicationFinanceByApplicationIdAndOrganisationId() { Long applicationId = 1L; Long organisationId = 1L; ApplicationFinanceResource applicationFinanceResource = ApplicationFinanceResourceBuilder.newApplicationFinanceResource().build(); when(applicationFinanceRestService.getApplicationFinance(applicationId, organisationId)).thenReturn(restSuccess(applicationFinanceResource)); ApplicationFinanceResource result = service.getApplicationFinanceByApplicationIdAndOrganisationId(applicationId, organisationId); assertEquals(applicationFinanceResource, result); }
### Question: FinanceServiceImpl implements FinanceService { @Override public ApplicationFinanceResource getApplicationFinanceDetails(Long userId, Long applicationId) { ProcessRoleResource userApplicationRole = userRestService.findProcessRole(userId, applicationId).getSuccess(); return getApplicationFinanceDetails(userId, applicationId, userApplicationRole.getOrganisationId()); } @Override ApplicationFinanceResource getApplicationFinance(Long userId, Long applicationId); @Override ApplicationFinanceResource getApplicationFinanceByApplicationIdAndOrganisationId(Long applicationId, Long organisationId); @Override ApplicationFinanceResource getApplicationFinanceDetails(Long userId, Long applicationId); @Override ApplicationFinanceResource getApplicationFinanceDetails(Long userId, Long applicationId, Long organisationId); @Override List<ApplicationFinanceResource> getApplicationFinanceDetails(Long applicationId); @Override List<ApplicationFinanceResource> getApplicationFinanceTotals(Long applicationId); @Override RestResult<FileEntryResource> getFinanceEntry(Long applicationFinanceFileEntryId); @Override RestResult<FileEntryResource> getFinanceEntryByApplicationFinanceId(Long applicationFinanceId); @Override RestResult<ByteArrayResource> getFinanceDocumentByApplicationFinance(Long applicationFinanceId); }### Answer: @Test public void testGetApplicationFinanceDetailsByApplicationId() { Long applicationId = 1L; List<ApplicationFinanceResource> applicationFinanceResources = ApplicationFinanceResourceBuilder.newApplicationFinanceResource().build(3); when(applicationFinanceRestService.getFinanceDetails(applicationId)).thenReturn(restSuccess(applicationFinanceResources)); List<ApplicationFinanceResource> result = service.getApplicationFinanceDetails(applicationId); assertEquals(applicationFinanceResources, result); }
### Question: ProjectServiceImpl implements ProjectService { @Override public ProjectResource getById(long projectId) { return projectRestService.getProjectById(projectId).getSuccess(); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getById() { ProjectResource projectResource = newProjectResource().build(); when(projectRestService.getProjectById(projectResource.getId())).thenReturn(restSuccess(projectResource)); ProjectResource returnedProjectResource = service.getById(projectResource.getId()); assertEquals(projectResource, returnedProjectResource); verify(projectRestService).getProjectById(projectResource.getId()); }
### Question: ProjectServiceImpl implements ProjectService { @Override public List<ProjectUserResource> getProjectUsersForProject(long projectId) { return projectRestService.getProjectUsersForProject(projectId).getSuccess(); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getProjectUsersForProject() { long projectId = 1; List<ProjectUserResource> projectUsers = newProjectUserResource().build(5); when(projectRestService.getProjectUsersForProject(projectId)).thenReturn(restSuccess(projectUsers)); List<ProjectUserResource> returnedProjectUsers = service.getProjectUsersForProject(projectId); assertEquals(returnedProjectUsers, projectUsers); verify(projectRestService).getProjectUsersForProject(projectId); }
### Question: ProjectServiceImpl implements ProjectService { @Override public ProjectResource getByApplicationId(long applicationId) { RestResult<ProjectResource> restResult = projectRestService.getByApplicationId(applicationId); if(restResult.isSuccess()){ return restResult.getSuccess(); } else { return null; } } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getByApplicationId() { ApplicationResource applicationResource = newApplicationResource().build(); ProjectResource projectResource = newProjectResource().withApplication(applicationResource).build(); when(projectRestService.getByApplicationId(applicationResource.getId())).thenReturn(restSuccess(projectResource)); ProjectResource returnedProjectResource = service.getByApplicationId(applicationResource.getId()); assertEquals(returnedProjectResource, projectResource); verify(projectRestService).getByApplicationId(applicationResource.getId()); }
### Question: ProjectServiceImpl implements ProjectService { @Override public OrganisationResource getLeadOrganisation(long projectId) { return projectRestService.getLeadOrganisationByProject(projectId).getSuccess(); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getLeadOrganisation() { OrganisationResource organisationResource = newOrganisationResource().build(); ApplicationResource applicationResource = newApplicationResource().build(); ProjectResource projectResource = newProjectResource().withApplication(applicationResource).build(); when(projectRestService.getLeadOrganisationByProject(projectResource.getId())).thenReturn(restSuccess(organisationResource)); OrganisationResource returnedOrganisationResource = service.getLeadOrganisation(projectResource.getId()); assertEquals(organisationResource, returnedOrganisationResource); verify(projectRestService).getLeadOrganisationByProject(projectResource.getId()); }
### Question: ProjectServiceImpl implements ProjectService { @Override public Optional<ProjectUserResource> getProjectManager(long projectId) { return projectRestService.getProjectManager(projectId).toServiceResult().getOptionalSuccessObject(); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getProjectManager() { long projectId = 123; long projectManagerId = 987; when(projectRestService.getProjectManager(projectId)) .thenReturn(restSuccess(newProjectUserResource().withUser(projectManagerId).build())); assertTrue(service.getProjectManager(projectId).isPresent()); } @Test public void getProjectManager_notFound() { long projectId = 123; when(projectRestService.getProjectManager(projectId)) .thenReturn(restSuccess(null, HttpStatus.NOT_FOUND)); assertFalse(service.getProjectManager(projectId).isPresent()); }
### Question: ProjectServiceImpl implements ProjectService { @Override public final Boolean isProjectManager(long userId, long projectId) { return getProjectManager(projectId).map(maybePM -> maybePM.isUser(userId)).orElse(false); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void isProjectManager() { final long projectId = 123; final long projectManagerId = 987; when(projectRestService.getProjectManager(projectId)) .thenReturn(restSuccess(newProjectUserResource().withUser(projectManagerId).build())); assertTrue(service.isProjectManager(projectManagerId, projectId)); }
### Question: ProjectServiceImpl implements ProjectService { @Override public Long getOrganisationIdFromUser(long projectId, UserResource user) throws ForbiddenActionException { RestResult<OrganisationResource> organisationResource = organisationRestService.getByUserAndProjectId(user.getId(), projectId); if (organisationResource.toServiceResult().isFailure()) { throw new ForbiddenActionException(CANNOT_GET_ANY_USERS_FOR_PROJECT.getErrorKey(), Collections.singletonList(projectId)); } return organisationResource.getSuccess().getId(); } @Override List<ProjectUserResource> getProjectUsersForProject(long projectId); @Override List<ProjectUserResource> getDisplayProjectUsersForProject(long projectId); @Override ProjectResource getById(long projectId); @Override ProjectResource getByApplicationId(long applicationId); @Override OrganisationResource getLeadOrganisation(long projectId); @Override List<OrganisationResource> getPartnerOrganisationsForProject(long projectId); @Override List<ProjectUserResource> getLeadPartners(long projectId); @Override List<ProjectUserResource> getPartners(long projectId); @Override boolean isUserLeadPartner(long projectId, long userId); @Override List<ProjectUserResource> getProjectUsersWithPartnerRole(long projectId); @Override Optional<ProjectUserResource> getProjectManager(long projectId); @Override final Boolean isProjectManager(long userId, long projectId); @Override Boolean isProjectFinanceContact(long userId, long projectId); @Override boolean userIsPartnerInOrganisationForProject(long projectId, long organisationId, long userId); @Override Long getOrganisationIdFromUser(long projectId, UserResource user); }### Answer: @Test public void getOrganisationIdFromUser() { long projectId = 1; long userId = 2; long expectedOrgId = 3; UserResource userResource = newUserResource().withId(userId).build(); setLoggedInUser(userResource); when(projectService.getOrganisationIdFromUser(projectId, userResource)).thenReturn(expectedOrgId); long organisationId = projectService.getOrganisationIdFromUser(projectId, userResource); assertEquals(expectedOrgId, organisationId); }
### Question: ControllersUtil { public static boolean isLeadPartner(final PartnerOrganisationRestService partnerOrganisationService, final Long projectId, final Long organisationId) { RestResult<List<PartnerOrganisationResource>> result = partnerOrganisationService.getProjectPartnerOrganisations(projectId); if(null != result && result.isSuccess()) { Optional<PartnerOrganisationResource> partnerOrganisationResource = simpleFindFirst(result.getSuccess(), PartnerOrganisationResource::isLeadOrganisation); return partnerOrganisationResource.isPresent() && partnerOrganisationResource.get().getOrganisation().equals(organisationId); } else { return false; } } private ControllersUtil(); static boolean isLeadPartner(final PartnerOrganisationRestService partnerOrganisationService, final Long projectId, final Long organisationId); }### Answer: @Test public void testIsLeadPartner() { Long projectId = 1L; Long organisationId = 2L; PartnerOrganisationResource partnerOrganisationResource = new PartnerOrganisationResource(); partnerOrganisationResource.setOrganisation(organisationId); partnerOrganisationResource.setLeadOrganisation(true); when(partnerOrganisationRestService.getProjectPartnerOrganisations(projectId)).thenReturn(restSuccess(singletonList(partnerOrganisationResource))); assertTrue(ControllersUtil.isLeadPartner(partnerOrganisationRestService, projectId, organisationId)); } @Test public void testNotLeadPartner() { Long projectId = 1L; Long organisationId = 2L; PartnerOrganisationResource partnerOrganisationResource = new PartnerOrganisationResource(); partnerOrganisationResource.setOrganisation(organisationId); partnerOrganisationResource.setLeadOrganisation(false); when(partnerOrganisationRestService.getProjectPartnerOrganisations(projectId)).thenReturn(restSuccess(singletonList(partnerOrganisationResource))); assertFalse(ControllersUtil.isLeadPartner(partnerOrganisationRestService, projectId, organisationId)); Long mismatchOrganisationId = 3L; partnerOrganisationResource.setOrganisation(mismatchOrganisationId); partnerOrganisationResource.setLeadOrganisation(true); assertFalse(ControllersUtil.isLeadPartner(partnerOrganisationRestService, projectId, organisationId)); }
### Question: StatusServiceImpl implements StatusService { @Override public ProjectTeamStatusResource getProjectTeamStatus(Long projectId, Optional<Long> filterByUserId) { return statusRestService.getProjectTeamStatus(projectId, filterByUserId).getSuccess(); } @Override ProjectTeamStatusResource getProjectTeamStatus(Long projectId, Optional<Long> filterByUserId); @Override ProjectStatusResource getProjectStatus(Long projectId); }### Answer: @Test public void testGetProjectTeamStatus() throws Exception { ProjectTeamStatusResource expectedProjectTeamStatusResource = newProjectTeamStatusResource().build(); when(statusRestService.getProjectTeamStatus(1L, Optional.empty())).thenReturn(restSuccess(expectedProjectTeamStatusResource)); ProjectTeamStatusResource projectTeamStatusResource = service.getProjectTeamStatus(1L, Optional.empty()); assertEquals(expectedProjectTeamStatusResource, projectTeamStatusResource); verify(statusRestService).getProjectTeamStatus(1L, Optional.empty()); } @Test public void testGetProjectTeamStatusWithFilterByUserId() throws Exception { ProjectTeamStatusResource expectedProjectTeamStatusResource = newProjectTeamStatusResource().build(); when(statusRestService.getProjectTeamStatus(1L, Optional.of(456L))).thenReturn(restSuccess(expectedProjectTeamStatusResource)); ProjectTeamStatusResource projectTeamStatusResource = service.getProjectTeamStatus(1L, Optional.of(456L)); assertEquals(expectedProjectTeamStatusResource, projectTeamStatusResource); verify(statusRestService).getProjectTeamStatus(1L, Optional.of(456L)); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId) { return projectDetailsRestService.updateFinanceContact(composite, financeContactUserId).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updateFinanceContact() { long projectId = 1L; long organisationId = 2L; long financeContactId = 3L; when(projectDetailsRestService.updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactId)).thenReturn(restSuccess()); service.updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactId); verify(projectDetailsRestService).updateFinanceContact(new ProjectOrganisationCompositeId(projectId, organisationId), financeContactId); verifyNoMoreInteractions(projectDetailsRestService); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown) { return projectDetailsRestService.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updatePartnerProjectLocation() { long projectId = 1L; long organisationId = 2L; PostcodeAndTownResource postcodeAndTown = new PostcodeAndTownResource("TW14 9QG", null); when(projectDetailsRestService.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown)).thenReturn(restSuccess()); ServiceResult<Void> result = service.updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown); assertTrue(result.isSuccess()); verify(projectDetailsRestService).updatePartnerProjectLocation(projectId, organisationId, postcodeAndTown); verifyNoMoreInteractions(projectDetailsRestService); }
### Question: GrantProcessServiceImpl implements GrantProcessService { @Override public void sendSucceeded(long applicationId) { GrantProcess process = grantProcessRepository.findOneByApplicationId(applicationId); grantProcessRepository.save(process.sendSucceeded(ZonedDateTime.now())); } @Override @Transactional(readOnly = true) Optional<GrantProcess> findByApplicationId(Long applicationId); @Override void createGrantProcess(long applicationId); @Override @Transactional(readOnly = true) List<GrantProcess> findReadyToSend(); @Override @Transactional(readOnly = true) Optional<GrantProcess> findOneReadyToSend(); @Override void sendSucceeded(long applicationId); @Override void sendFailed(long applicationId, String message); }### Answer: @Test public void sendSucceeded() { ZonedDateTime now = ZonedDateTime.now(); long applicationId = 7L; GrantProcess grantProcess = new GrantProcess(applicationId); when(grantProcessRepository.findOneByApplicationId(applicationId)).thenReturn(grantProcess); when(grantProcessRepository.save(grantProcess)).thenReturn(grantProcess); service.sendSucceeded(applicationId); verify(grantProcessRepository).findOneByApplicationId(applicationId); verify(grantProcessRepository).save(createLambdaMatcher(g -> { assertEquals(applicationId, g.getApplicationId()); assertFalse(g.isPending()); assertNull(g.getMessage()); assertNull(g.getSentRequested()); assertNotNull(g.getSentSucceeded()); assertNull(g.getLastProcessed()); })); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId) { return projectDetailsRestService.updateProjectManager(projectId, projectManagerUserId).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updateProjectManager() { when(projectDetailsRestService.updateProjectManager(1L, 2L)).thenReturn(restSuccess()); service.updateProjectManager(1L, 2L); verify(projectDetailsRestService).updateProjectManager(1L, 2L); verifyNoMoreInteractions(projectDetailsRestService); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate) { return projectDetailsRestService.updateProjectStartDate(projectId, projectStartDate).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updateProjectStartDate() { LocalDate date = LocalDate.now(); when(projectDetailsRestService.updateProjectStartDate(1L, date)).thenReturn(restSuccess()); ServiceResult<Void> result = service.updateProjectStartDate(1L, date); assertTrue(result.isSuccess()); verify(projectDetailsRestService).updateProjectStartDate(1L, date); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths) { return projectDetailsRestService.updateProjectDuration(projectId, durationInMonths).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updateProjectDuration() { long projectId = 3L; long durationInMonths = 18L; when(projectDetailsRestService.updateProjectDuration(projectId, durationInMonths)).thenReturn(restSuccess()); ServiceResult<Void> result = service.updateProjectDuration(projectId, durationInMonths); assertTrue(result.isSuccess()); verify(projectDetailsRestService).updateProjectDuration(projectId, durationInMonths); verifyNoMoreInteractions(projectDetailsRestService); }
### Question: ProjectDetailsServiceImpl implements ProjectDetailsService { @Override public ServiceResult<Void> updateAddress(Long projectId, AddressResource address) { return projectDetailsRestService.updateProjectAddress(projectId, address).toServiceResult(); } @Override ServiceResult<Void> updateProjectManager(Long projectId, Long projectManagerUserId); @Override ServiceResult<Void> updateFinanceContact(ProjectOrganisationCompositeId composite, Long financeContactUserId); @Override ServiceResult<Void> updatePartnerProjectLocation(long projectId, long organisationId, PostcodeAndTownResource postcodeAndTown); @Override ServiceResult<Void> updateProjectStartDate(long projectId, LocalDate projectStartDate); @Override ServiceResult<Void> updateProjectDuration(long projectId, long durationInMonths); @Override ServiceResult<Void> updateAddress(Long projectId, AddressResource address); }### Answer: @Test public void updateAddress() { long leadOrgId = 1L; long projectId = 2L; AddressResource addressResource = newAddressResource().build(); when(projectDetailsRestService.updateProjectAddress(projectId, addressResource)).thenReturn(restSuccess()); ServiceResult<Void> result = service.updateAddress(projectId, addressResource); assertTrue(result.isSuccess()); verify(projectDetailsRestService).updateProjectAddress(projectId, addressResource); verifyNoMoreInteractions(projectDetailsRestService); }
### Question: FinanceCheckServiceImpl implements FinanceCheckService { @Override public FinanceCheckResource getByProjectAndOrganisation(ProjectOrganisationCompositeId key) { return financeCheckRestService.getByProjectAndOrganisation(key.getProjectId(), key.getOrganisationId()).getSuccess(); } @Override FinanceCheckResource getByProjectAndOrganisation(ProjectOrganisationCompositeId key); @Override ServiceResult<FinanceCheckSummaryResource> getFinanceCheckSummary(Long projectId); @Override ServiceResult<FinanceCheckOverviewResource> getFinanceCheckOverview(Long projectId); @Override FinanceCheckEligibilityResource getFinanceCheckEligibilityDetails(Long projectId, Long organisationId); @Override ServiceResult<AttachmentResource> uploadFile(Long projectId, String contentType, long contentLength, String originalFilename, byte[] bytes); @Override ServiceResult<Void> deleteFile(Long fileId); @Override ByteArrayResource downloadFile(Long fileId); @Override ServiceResult<AttachmentResource> getAttachment(Long attachmentId); @Override FileEntryResource getAttachmentInfo(Long attachmentId); @Override ServiceResult<Long> saveQuery(QueryResource query); @Override ServiceResult<List<QueryResource>> getQueries(Long projectFinanceId); @Override ServiceResult<Void> saveQueryPost(PostResource post, long threadId); @Override ServiceResult<Void> closeQuery(Long queryId); @Override ServiceResult<Long> saveNote(NoteResource note); @Override ServiceResult<List<NoteResource>> loadNotes(Long projectFinanceId); @Override ServiceResult<Void> saveNotePost(PostResource post, long noteId); }### Answer: @Test public void testGet(){ Long projectId = 123L; Long organisationId = 456L; ProjectOrganisationCompositeId key = new ProjectOrganisationCompositeId(projectId, organisationId); FinanceCheckResource financeCheckResource = newFinanceCheckResource().build(); when(financeCheckRestServiceMock.getByProjectAndOrganisation(projectId, organisationId)).thenReturn(restSuccess(financeCheckResource)); FinanceCheckResource result = service.getByProjectAndOrganisation(key); assertEquals(financeCheckResource, result); }
### Question: FinanceCheckServiceImpl implements FinanceCheckService { @Override public ServiceResult<Void> closeQuery(Long queryId) { return queryService.close(queryId).toServiceResult(); } @Override FinanceCheckResource getByProjectAndOrganisation(ProjectOrganisationCompositeId key); @Override ServiceResult<FinanceCheckSummaryResource> getFinanceCheckSummary(Long projectId); @Override ServiceResult<FinanceCheckOverviewResource> getFinanceCheckOverview(Long projectId); @Override FinanceCheckEligibilityResource getFinanceCheckEligibilityDetails(Long projectId, Long organisationId); @Override ServiceResult<AttachmentResource> uploadFile(Long projectId, String contentType, long contentLength, String originalFilename, byte[] bytes); @Override ServiceResult<Void> deleteFile(Long fileId); @Override ByteArrayResource downloadFile(Long fileId); @Override ServiceResult<AttachmentResource> getAttachment(Long attachmentId); @Override FileEntryResource getAttachmentInfo(Long attachmentId); @Override ServiceResult<Long> saveQuery(QueryResource query); @Override ServiceResult<List<QueryResource>> getQueries(Long projectFinanceId); @Override ServiceResult<Void> saveQueryPost(PostResource post, long threadId); @Override ServiceResult<Void> closeQuery(Long queryId); @Override ServiceResult<Long> saveNote(NoteResource note); @Override ServiceResult<List<NoteResource>> loadNotes(Long projectFinanceId); @Override ServiceResult<Void> saveNotePost(PostResource post, long noteId); }### Answer: @Test public void testCloseQuery(){ Long queryId = 1L; when(projectFinanceQueriesRestServiceMock.close(queryId)).thenReturn(restSuccess()); ServiceResult<Void> result = service.closeQuery(queryId); assertTrue(result.isSuccess()); verify(projectFinanceQueriesRestServiceMock).close(queryId); }
### Question: InternalProjectSetupRowPopulator { public List<InternalProjectSetupRow> populate(List<ProjectStatusResource> projectStatusResources, CompetitionResource competition, UserResource user) { return projectStatusResources.stream() .map(status -> new InternalProjectSetupRow( status.getProjectTitle(), status.getApplicationNumber(), status.getProjectState(), status.getNumberOfPartners(), competition.getId(), status.getProjectLeadOrganisationName(), status.getProjectNumber(), getProjectCells(status, competition.getProjectSetupStages(), user, competition.getId()), ProjectActivityStates.COMPLETE == status.getGrantOfferLetterStatus(), status.isSentToIfsPa() )).collect(Collectors.toList()); } List<InternalProjectSetupRow> populate(List<ProjectStatusResource> projectStatusResources, CompetitionResource competition, UserResource user); }### Answer: @Test public void populate() { UserResource userResource = newUserResource().build(); List<ProjectSetupStage> projectSetupStages = asList(PROJECT_DETAILS, PROJECT_TEAM); CompetitionResource competitionResource = newCompetitionResource() .withProjectSetupStages(projectSetupStages) .build(); List<ProjectStatusResource> projectStatusResources = newProjectStatusResource() .withProjectTitles("project title") .withApplicationNumber(1L) .withProjectState(ProjectState.LIVE) .withNumberOfPartners(1) .withProjectLeadOrganisationName("Org name") .withProjectNumber(1L) .build(3); List<InternalProjectSetupRow> rows = populator.populate(projectStatusResources, competitionResource, userResource); Set<InternalProjectSetupCell> cells = rows.stream() .map(InternalProjectSetupRow::getStates) .findFirst().get(); assertEquals(2, cells.size()); List<ProjectSetupStage> stages = cells.stream() .map(InternalProjectSetupCell::getStage) .collect(Collectors.toList()); assertTrue(stages.contains(PROJECT_DETAILS)); assertTrue(stages.contains(PROJECT_TEAM)); }
### Question: GrantProcessServiceImpl implements GrantProcessService { @Override public void sendFailed(long applicationId, String message) { GrantProcess process = grantProcessRepository.findOneByApplicationId(applicationId); grantProcessRepository.save(process.sendFailed(ZonedDateTime.now(), message)); } @Override @Transactional(readOnly = true) Optional<GrantProcess> findByApplicationId(Long applicationId); @Override void createGrantProcess(long applicationId); @Override @Transactional(readOnly = true) List<GrantProcess> findReadyToSend(); @Override @Transactional(readOnly = true) Optional<GrantProcess> findOneReadyToSend(); @Override void sendSucceeded(long applicationId); @Override void sendFailed(long applicationId, String message); }### Answer: @Test public void sendFailed() { ZonedDateTime now = ZonedDateTime.now(); long applicationId = 7L; String message = "message"; GrantProcess grantProcess = new GrantProcess(applicationId); when(grantProcessRepository.findOneByApplicationId(applicationId)).thenReturn(grantProcess); when(grantProcessRepository.save(grantProcess)).thenReturn(grantProcess); service.sendFailed(applicationId, message); verify(grantProcessRepository).findOneByApplicationId(applicationId); verify(grantProcessRepository).save(createLambdaMatcher(g -> { assertEquals(applicationId, g.getApplicationId()); assertFalse(g.isPending()); assertEquals(message, g.getMessage()); assertNull(g.getSentRequested()); assertNull(g.getSentSucceeded()); assertNotNull(g.getLastProcessed()); })); }
### Question: GrantProcessServiceImpl implements GrantProcessService { @Override @Transactional(readOnly = true) public Optional<GrantProcess> findByApplicationId(Long applicationId) { return Optional.ofNullable(grantProcessRepository.findOneByApplicationId(applicationId)); } @Override @Transactional(readOnly = true) Optional<GrantProcess> findByApplicationId(Long applicationId); @Override void createGrantProcess(long applicationId); @Override @Transactional(readOnly = true) List<GrantProcess> findReadyToSend(); @Override @Transactional(readOnly = true) Optional<GrantProcess> findOneReadyToSend(); @Override void sendSucceeded(long applicationId); @Override void sendFailed(long applicationId, String message); }### Answer: @Test public void getByApplicationIdNotPresent() { long applicationId = 7L; when(grantProcessRepository.findOneByApplicationId(applicationId)).thenReturn(null); Optional<GrantProcess> result = service.findByApplicationId(applicationId); assertFalse(result.isPresent()); } @Test public void getByApplicationIdPresent() { long applicationId = 7L; GrantProcess grantProcess = new GrantProcess(applicationId); when(grantProcessRepository.findOneByApplicationId(applicationId)).thenReturn(grantProcess); Optional<GrantProcess> result = service.findByApplicationId(applicationId); assertTrue(result.isPresent()); assertEquals(grantProcess, result.get()); }
### Question: ProjectFinanceServiceImpl implements ProjectFinanceService { @Override public List<ProjectFinanceResource> getProjectFinances(Long projectId) { return projectFinanceRestService.getProjectFinances(projectId).getSuccess(); } @Override List<ProjectFinanceResource> getProjectFinances(Long projectId); @Override ViabilityResource getViability(Long projectId, Long organisationId); @Override ServiceResult<Void> saveViability(Long projectId, Long organisationId, ViabilityState viability, ViabilityRagStatus viabilityRagRating); @Override EligibilityResource getEligibility(Long projectId, Long organisationId); @Override ServiceResult<Void> saveEligibility(Long projectId, Long organisationId, EligibilityState eligibility, EligibilityRagStatus eligibilityRagStatus); @Override boolean isCreditReportConfirmed(Long projectId, Long organisationId); @Override ServiceResult<Void> saveCreditReportConfirmed(Long projectId, Long organisationId, boolean confirmed); @Override ProjectFinanceResource getProjectFinance(Long projectId, Long organisationId); @Override ServiceResult<Boolean> hasAnyProjectOrganisationSizeChangedFromApplication(long projectId); }### Answer: @Test public void testGetProjectFinances() { List<ProjectFinanceResource> resources = newProjectFinanceResource().build(2); when(projectFinanceRestService.getProjectFinances(123L)).thenReturn(restSuccess(resources)); List<ProjectFinanceResource> financeTotals = service.getProjectFinances(123L); assertEquals(resources, financeTotals); }