下面列出了怎么用org.mockito.internal.util.reflection.FieldSetter的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
void revokeConsent() throws NoSuchFieldException {
// Given
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(FINALISED, ConsentStatus.RECEIVED));
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(cmsPsuAisClient.updateAuthorisationStatus(anyString(), anyString(), anyString(), anyString(), ArgumentMatchers.nullable(String.class), ArgumentMatchers.nullable(String.class), ArgumentMatchers.nullable(String.class), anyString(), any())).thenReturn(ResponseEntity.ok(null));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.revokeConsent(ENCRYPTED_ID, AUTH_ID, COOKIE);
// Then
assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(false, false, true, ScaStatusTO.EXEMPTED)), result);
}
@Test
void handlePaymentAuthorizeException() throws NoSuchFieldException {
// Given
FieldSetter.setField(service, service.getClass().getDeclaredField("objectMapper"), STATIC_MAPPER);
PaymentAuthorizeResponse authorizeResponse = new PaymentAuthorizeResponse(new PaymentTO());
PsuMessage message = new PsuMessage();
message.setCode("400");
message.setText("Msg");
authorizeResponse.setPsuMessages(List.of(message));
// When
ResponseEntity<Map> result = service.handlePaymentAuthorizeException(new PaymentAuthorizeException(ResponseEntity.status(HttpStatus.NOT_FOUND).body(authorizeResponse)));
// Then
compareBodies(result, ResponseEntity.status(HttpStatus.BAD_REQUEST).body(getExpected(400, "Msg")));
}
@Test
void getTest() throws NoSuchFieldException {
SdxCluster sdxCluster = getValidSdxCluster();
when(sdxService.getSdxByNameInAccount(anyString(), anyString())).thenReturn(sdxCluster);
SdxStatusEntity sdxStatusEntity = new SdxStatusEntity();
sdxStatusEntity.setStatus(DatalakeStatusEnum.REQUESTED);
sdxStatusEntity.setStatusReason("statusreason");
sdxStatusEntity.setCreated(1L);
when(sdxStatusService.getActualStatusForSdx(sdxCluster)).thenReturn(sdxStatusEntity);
FieldSetter.setField(sdxClusterConverter, SdxClusterConverter.class.getDeclaredField("sdxStatusService"), sdxStatusService);
SdxClusterResponse sdxClusterResponse = ThreadBasedUserCrnProvider.doAs(USER_CRN, () -> sdxController.get("test-sdx-cluster"));
assertEquals("test-sdx-cluster", sdxClusterResponse.getName());
assertEquals("test-env", sdxClusterResponse.getEnvironmentName());
assertEquals("crn:sdxcluster", sdxClusterResponse.getCrn());
assertEquals(SdxClusterStatusResponse.REQUESTED, sdxClusterResponse.getStatus());
assertEquals("statusreason", sdxClusterResponse.getStatusReason());
}
public void process(Class<?> clazz, Object testInstance) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
boolean alreadyAssigned = false;
for(Annotation annotation : field.getAnnotations()) {
Object mock = createMockFor(annotation, field);
if (mock != null) {
throwIfAlreadyAssigned(field, alreadyAssigned);
alreadyAssigned = true;
try {
new FieldSetter(testInstance, field).set(mock);
} catch (Exception e) {
throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
+ annotation, e);
}
}
}
}
}
@Test
void fromRequest() throws NoSuchFieldException {
// Given
FieldSetter.setField(defaultConsentReferencePolicy, defaultConsentReferencePolicy.getClass().getDeclaredField("hmacSecret"), "6VFX8YFQG5DLFKZIMNLGH9P406XR1SY4");
ConsentReference reference = defaultConsentReferencePolicy.fromURL(REDIRECT_ID, CONSENT_TYPE_AIS, ENCRYPTED_CONSENT_ID);
// When
ConsentReference consentReference = defaultConsentReferencePolicy.fromRequest(ENCRYPTED_CONSENT_ID, AUTHORIZATION_ID, reference.getCookieString(), false);
// Then
assertNotNull(consentReference);
assertEquals(AUTHORIZATION_ID, consentReference.getAuthorizationId());
assertEquals(REDIRECT_ID, consentReference.getRedirectId());
assertEquals(CONSENT_TYPE_AIS, consentReference.getConsentType());
assertEquals(ENCRYPTED_CONSENT_ID, consentReference.getEncryptedConsentId());
assertNotNull(consentReference.getCookieString());
}
@Before
public void initializeSendGridMock() throws Exception {
new FieldSetter(uut, uut.getClass().getDeclaredField("sendGrid")).set(sendGrid);
new FieldSetter(uut, uut.getClass().getDeclaredField("logger")).set(logger);
Map<String, String> renderedParts = new HashMap<String, String>();
renderedParts.put("", expectedEmailBody);
notification = new NotificationBuilder().withPersonId(personId).withPlaceId(placeId).build();
Map<String, BaseEntity<?, ?>> entityMap = new HashMap<>(2);
entityMap.put(NotificationProviderUtil.RECIPIENT_KEY, person);
entityMap.put(NotificationProviderUtil.PLACE_KEY, place);
Mockito.when(personDao.findById(Mockito.any())).thenReturn(person);
Mockito.when(placeDao.findById(placeId)).thenReturn(place);
Mockito.when(person.getEmail()).thenReturn(expectedEmailFromEmail);
Mockito.when(person.getFirstName()).thenReturn(expectedFirstName);
Mockito.when(person.getLastName()).thenReturn(expectedLastName);
Mockito.when(messageRenderer.renderMessage(notification, NotificationMethod.EMAIL, person, entityMap)).thenReturn(expectedEmailBody);
Mockito.when(messageRenderer.renderMultipartMessage(notification, NotificationMethod.EMAIL, person, entityMap)).thenReturn(renderedParts);
Mockito.when(sendGrid.api(Mockito.any())).thenReturn(response);
}
@Before
public void setUp() throws NoSuchFieldException {
given(tcString.getVendorListVersion()).willReturn(10);
given(purposeStrategyOne.getPurposeId()).willReturn(1);
given(purposeStrategyTwo.getPurposeId()).willReturn(2);
given(purposeStrategyFour.getPurposeId()).willReturn(4);
given(purposeStrategySeven.getPurposeId()).willReturn(7);
purposeStrategies = asList(purposeStrategyOne, purposeStrategyTwo, purposeStrategyFour, purposeStrategySeven);
given(specialFeaturesStrategyOne.getSpecialFeatureId()).willReturn(1);
specialFeaturesStrategies = singletonList(specialFeaturesStrategyOne);
given(vendorListService.forVersion(anyInt())).willReturn(Future.succeededFuture(emptyMap()));
initPurposes();
initSpecialFeatures();
initGdpr();
target = new Tcf2Service(gdprConfig, vendorListService, bidderCatalog);
FieldSetter.setField(target,
target.getClass().getDeclaredField("supportedPurposeStrategies"), purposeStrategies);
FieldSetter.setField(target,
target.getClass().getDeclaredField("supportedSpecialFeatureStrategies"), specialFeaturesStrategies);
}
private void processInjectAnnotation(Class clazz){
Set<Field> mockDependentFields = new HashSet<Field>();
new InjectAnnotationScanner(clazz, Inject.class).addTo(mockDependentFields);
new InjectAnnotationScanner(clazz, InjectOnlyTest.class).addTo(mockDependentFields);
for(Field f : mockDependentFields){
FieldReader fr = new FieldReader(owner, f);
Object value = null;
if(!fr.isNull()){
value = fr.read();
}
boolean isMockOrSpy = isMockOrSpy(value);
if(value != null && isMockOrSpy){
Mockito.reset(value);
continue;
}
if(value == null){
value = Mockito.spy(f.getType());
}
//spy会新生成对象,导致从容器中脱离
//else{
// value = Mockito.spy(value);
//}
new FieldSetter(owner, f).set(value);
}
}
@Test
public void assertCompareToForAsc() throws SQLException, NoSuchFieldException {
SelectStatement selectStatement = new SelectStatement();
ProjectionsSegment projectionsSegment = new ProjectionsSegment(0, 0);
selectStatement.setProjections(projectionsSegment);
SelectStatementContext selectStatementContext = new SelectStatementContext(
selectStatement, new GroupByContext(Collections.emptyList(), 0), createOrderBy(), createProjectionsContext(), null);
SchemaMetaData schemaMetaData = mock(SchemaMetaData.class);
QueryResult queryResult1 = createQueryResult("1", "2");
OrderByValue orderByValue1 = new OrderByValue(queryResult1, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue1, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue1.next());
QueryResult queryResult2 = createQueryResult("3", "4");
OrderByValue orderByValue2 = new OrderByValue(queryResult2, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue2, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue2.next());
assertTrue(orderByValue1.compareTo(orderByValue2) < 0);
assertFalse(orderByValue1.getQueryResult().next());
assertFalse(orderByValue2.getQueryResult().next());
}
@Test
public void assertCompareToForDesc() throws SQLException, NoSuchFieldException {
SelectStatement selectStatement = new SelectStatement();
ProjectionsSegment projectionsSegment = new ProjectionsSegment(0, 0);
selectStatement.setProjections(projectionsSegment);
SelectStatementContext selectStatementContext = new SelectStatementContext(
selectStatement, new GroupByContext(Collections.emptyList(), 0), createOrderBy(), createProjectionsContext(), null);
SchemaMetaData schemaMetaData = mock(SchemaMetaData.class);
QueryResult queryResult1 = createQueryResult("1", "2");
OrderByValue orderByValue1 = new OrderByValue(queryResult1, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue1, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue1.next());
QueryResult queryResult2 = createQueryResult("3", "4");
OrderByValue orderByValue2 = new OrderByValue(queryResult2, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue2, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue2.next());
assertTrue(orderByValue1.compareTo(orderByValue2) > 0);
assertFalse(orderByValue1.getQueryResult().next());
assertFalse(orderByValue2.getQueryResult().next());
}
@Test
public void assertCompareToWhenEqual() throws SQLException, NoSuchFieldException {
SelectStatement selectStatement = new SelectStatement();
ProjectionsSegment projectionsSegment = new ProjectionsSegment(0, 0);
selectStatement.setProjections(projectionsSegment);
SelectStatementContext selectStatementContext = new SelectStatementContext(
selectStatement, new GroupByContext(Collections.emptyList(), 0), createOrderBy(), createProjectionsContext(), null);
SchemaMetaData schemaMetaData = mock(SchemaMetaData.class);
QueryResult queryResult1 = createQueryResult("1", "2");
OrderByValue orderByValue1 = new OrderByValue(queryResult1, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue1, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue1.next());
QueryResult queryResult2 = createQueryResult("1", "2");
OrderByValue orderByValue2 = new OrderByValue(queryResult2, Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))),
selectStatementContext, schemaMetaData);
FieldSetter.setField(orderByValue2, OrderByValue.class.getDeclaredField("orderValuesCaseSensitive"), Arrays.asList(false, false));
assertTrue(orderByValue2.next());
assertThat(orderByValue1.compareTo(orderByValue2), is(0));
assertFalse(orderByValue1.getQueryResult().next());
assertFalse(orderByValue2.getQueryResult().next());
}
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
if(mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
return new OngoingInjecter() {
public boolean thenInject() {
try {
if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
new FieldSetter(fieldInstance, field).set(matchingMock);
}
} catch (Exception e) {
throw new MockitoException("Problems injecting dependency in " + field.getName(), e);
}
return true;
}
};
}
return new OngoingInjecter() {
public boolean thenInject() {
return false;
}
};
}
public void process(Class<?> clazz, Object testClass) {
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
boolean alreadyAssigned = false;
for(Annotation annotation : field.getAnnotations()) {
Object mock = createMockFor(annotation, field);
if (mock != null) {
throwIfAlreadyAssigned(field, alreadyAssigned);
alreadyAssigned = true;
try {
new FieldSetter(testClass, field).set(mock);
} catch (Exception e) {
throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
+ annotation, e);
}
}
}
}
}
@SuppressWarnings("deprecation")
static void processAnnotationDeprecatedWay(AnnotationEngine annotationEngine, Object testClass, Field field) {
boolean alreadyAssigned = false;
for(Annotation annotation : field.getAnnotations()) {
Object mock = annotationEngine.createMockFor(annotation, field);
if (mock != null) {
throwIfAlreadyAssigned(field, alreadyAssigned);
alreadyAssigned = true;
try {
new FieldSetter(testClass, field).set(mock);
} catch (Exception e) {
throw new MockitoException("Problems setting field " + field.getName() + " annotated with "
+ annotation, e);
}
}
}
}
public OngoingInjecter filterCandidate(final Collection<Object> mocks, final Field field, final Object fieldInstance) {
if(mocks.size() == 1) {
final Object matchingMock = mocks.iterator().next();
return new OngoingInjecter() {
public Object thenInject() {
try {
if (!new BeanPropertySetter(fieldInstance, field).set(matchingMock)) {
new FieldSetter(fieldInstance, field).set(matchingMock);
}
} catch (RuntimeException e) {
new Reporter().cannotInjectDependency(field, matchingMock, e);
}
return matchingMock;
}
};
}
return new OngoingInjecter() {
public Object thenInject() {
return null;
}
};
}
@Test
void handleFeignException() throws NoSuchMethodException, JsonProcessingException, NoSuchFieldException {
// Given
FieldSetter.setField(service, service.getClass().getDeclaredField("objectMapper"), STATIC_MAPPER);
// When
ResponseEntity<Map> result = service.handleFeignException(FeignException.errorStatus("method", getResponse()), new HandlerMethod(service, "toString", null));
ResponseEntity<Map<String, String>> expected = ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(getExpected(401, "status 401 reading method"));
// Then
compareBodies(result, expected);
}
@Test
void getDefaultData() throws NoSuchFieldException {
// Given
FieldSetter.setField(parseService, parseService.getClass().getDeclaredField("resourceLoader"), LOCAL_LOADER);
// When
Optional<DataPayload> data = parseService.getDefaultData();
// Then
assertTrue(data.isPresent());
}
@Test
void startConsentAuth() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(PSUIDENTIFIED, ConsentStatus.RECEIVED));
when(accountRestClient.getListOfAccounts()).thenReturn(ResponseEntity.ok(new ArrayList<>()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.startConsentAuth(ENCRYPTED_ID, AUTH_ID, COOKIE, getAisConsentTO(false));
// Then
assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, PSUIDENTIFIED)), result);
}
@Test
void startConsentAuth_exempted() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(EXEMPTED, ConsentStatus.RECEIVED));
when(accountRestClient.getListOfAccounts()).thenReturn(ResponseEntity.ok(new ArrayList<>()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.startConsentAuth(ENCRYPTED_ID, AUTH_ID, COOKIE, getAisConsentTO(false));
// Then
assertEquals(ResponseEntity.badRequest().build(), result);
}
@Test
void startConsentAuth_received() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(RECEIVED, ConsentStatus.RECEIVED));
when(accountRestClient.getListOfAccounts()).thenReturn(ResponseEntity.ok(new ArrayList<>()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.startConsentAuth(ENCRYPTED_ID, AUTH_ID, COOKIE, getAisConsentTO(false));
// Then
assertEquals(ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(), result);
}
@Test
void startConsentAuth_fail() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenThrow(new ConsentAuthorizeException(ResponseEntity.badRequest().build()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.startConsentAuth(ENCRYPTED_ID, AUTH_ID, COOKIE, getAisConsentTO(false));
// Then
assertEquals(ResponseEntity.badRequest().build(), result);
}
@Test
void authrizedConsent() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(FINALISED, ConsentStatus.RECEIVED));
when(consentRestClient.authorizeConsent(anyString(), anyString(), anyString())).thenReturn(ResponseEntity.ok(getScaConsentResponse(FINALISED)));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.authrizedConsent(ENCRYPTED_ID, AUTH_ID, COOKIE, CODE);
// Then
assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, FINALISED)), result);
}
@Test
void authrizedConsent_error() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenThrow(new ConsentAuthorizeException(ResponseEntity.badRequest().build()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.authrizedConsent(ENCRYPTED_ID, AUTH_ID, COOKIE, CODE);
// Then
assertEquals(ResponseEntity.badRequest().build(), result);
}
@Test
void selectMethod() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getConsentWorkflow(SCAMETHODSELECTED, ConsentStatus.RECEIVED));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.selectMethod(ENCRYPTED_ID, AUTH_ID, METHOD_ID, COOKIE);
// Then
assertEquals(ResponseEntity.ok(getConsentAuthorizeResponse(true, true, false, SCAMETHODSELECTED)), result);
}
@Test
void selectMethod_error() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenThrow(new ConsentAuthorizeException(ResponseEntity.badRequest().build()));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.selectMethod(ENCRYPTED_ID, AUTH_ID, METHOD_ID, COOKIE);
// Then
assertEquals(ResponseEntity.badRequest().build(), result);
}
@Test
void getListOfAccounts() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(accountRestClient.getListOfAccounts()).thenReturn(ResponseEntity.ok(getAccounts()));
// When
ResponseEntity<List<AccountDetailsTO>> result = controller.getListOfAccounts(COOKIE);
// Then
assertEquals(ResponseEntity.ok(getAccounts()), result);
}
@Test
void revokeConsent_error() throws NoSuchFieldException {
// Given
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(redirectConsentService.identifyConsent(anyString(), anyString(), anyBoolean(), anyString(), any())).thenThrow(new ConsentAuthorizeException(ResponseEntity.badRequest().build()));
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
// When
ResponseEntity<ConsentAuthorizeResponse> result = controller.revokeConsent(ENCRYPTED_ID, AUTH_ID, COOKIE);
// Then
assertEquals(ResponseEntity.badRequest().build(), result);
}
@Test
void selectMethod() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(paymentService.selectScaForPayment(anyString(), anyString(), anyString(), anyString(), anyBoolean(), anyString(), any())).thenReturn(getPaymentWorkflow(SCAMETHODSELECTED, ACSP));
// When
ResponseEntity<PaymentAuthorizeResponse> result = controller.selectMethod(ENCRYPTED_ID, AUTH_ID, METHOD_ID, COOKIE);
// Then
assertEquals(ResponseEntity.ok(getPaymentAuthorizeResponse(true, true, SCAMETHODSELECTED)), result);
}
@Test
void authorisePayment() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(paymentService.identifyPayment(anyString(), anyString(), anyBoolean(), anyString(), anyString(), any())).thenReturn(getPaymentWorkflow(PSUIDENTIFIED, ACSP));
when(paymentService.authorizeCancelPayment(any(), anyString(), anyString())).thenReturn(getPaymentWorkflow(FINALISED, ACSP));
// When
ResponseEntity<PaymentAuthorizeResponse> result = controller.authorisePayment(ENCRYPTED_ID, AUTH_ID, METHOD_ID, COOKIE);
// Then
assertEquals(ResponseEntity.ok(getPaymentAuthorizeResponse(true, true, FINALISED)), result);
}
@Test
void pisDone() throws NoSuchFieldException {
// Given
FieldSetter.setField(controller, controller.getClass().getDeclaredField("middlewareAuth"), new ObaMiddlewareAuthentication(null, new BearerTokenTO(TOKEN, null, 999, null, getAccessTokenTO())));
when(responseUtils.consentCookie(any())).thenReturn(COOKIE);
when(paymentService.resolveRedirectUrl(anyString(), anyString(), anyString(), anyBoolean(), anyString(), any(), anyString())).thenReturn(NOK_URI);
when(responseUtils.redirect(anyString(), any())).thenReturn(ResponseEntity.ok(getPaymentAuthorizeResponse(false, false, FAILED)));
// When
ResponseEntity<PaymentAuthorizeResponse> result = controller.pisDone(ENCRYPTED_ID, AUTH_ID, COOKIE, false, "code");
// Then
assertEquals(ResponseEntity.ok(getPaymentAuthorizeResponse(true, true, FAILED)), result);
}