org.mockito.internal.util.reflection.FieldSetter Java Examples

The following examples show how to use org.mockito.internal.util.reflection.FieldSetter. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: FinalMockCandidateFilter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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;
        }
    };

}
 
Example #2
Source File: AISControllerTest.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: DefaultConsentReferencePolicyTest.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: GlobalExceptionHandlerTest.java    From XS2A-Sandbox with Apache License 2.0 6 votes vote down vote up
@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")));
}
 
Example #5
Source File: SdxControllerTest.java    From cloudbreak with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #6
Source File: DefaultAnnotationEngine.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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);
                }
            }        
        }
    }
}
 
Example #7
Source File: EmailProviderTest.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
@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);

}
 
Example #8
Source File: Tcf2ServiceTest.java    From prebid-server-java with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: SpyHelper.java    From COLA with GNU Lesser General Public License v2.1 6 votes vote down vote up
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);
    }
}
 
Example #10
Source File: OrderByValueTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #11
Source File: OrderByValueTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #12
Source File: OrderByValueTest.java    From shardingsphere with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #13
Source File: FinalMockCandidateFilter.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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;
        }
    };

}
 
Example #14
Source File: DefaultAnnotationEngine.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
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);
                }
            }        
        }
    }
}
 
Example #15
Source File: MockitoAnnotations.java    From astor with GNU General Public License v2.0 6 votes vote down vote up
@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);
            }
        }
    }
}
 
Example #16
Source File: AISControllerTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: EtcdCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({NoSuchFieldException.class, SecurityException.class})
private WatchResponse buildWatchResponse(final WatchEvent.EventType eventType) {
    WatchResponse watchResponse = new WatchResponse(mock(io.etcd.jetcd.api.WatchResponse.class), ByteSequence.EMPTY);
    List<WatchEvent> events = new ArrayList<>();
    io.etcd.jetcd.api.KeyValue keyValue1 = io.etcd.jetcd.api.KeyValue.newBuilder()
            .setKey(ByteString.copyFromUtf8("key1"))
            .setValue(ByteString.copyFromUtf8("value1")).build();
    KeyValue keyValue = new KeyValue(keyValue1, ByteSequence.EMPTY);
    events.add(new WatchEvent(keyValue, mock(KeyValue.class), eventType));
    FieldSetter.setField(watchResponse, watchResponse.getClass().getDeclaredField("events"), events);
    return watchResponse;
}
 
Example #18
Source File: ApolloOpenApiWrapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows({NoSuchFieldException.class, SecurityException.class})
@Before
public void setUp() {
    Properties props = new Properties();
    props.setProperty(ApolloPropertyKey.PORTAL_URL.getKey(), PORTAL_URL);
    props.setProperty(ApolloPropertyKey.TOKEN.getKey(), TOKEN);
    apolloOpenApiWrapper = new ApolloOpenApiWrapper(new CenterConfiguration("apollo", new Properties()), new ApolloProperties(props));
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("client"), client);
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("namespace"), NAME_SPACE);
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("appId"), ApolloPropertyKey.APP_ID.getDefaultValue());
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("env"), ApolloPropertyKey.ENV.getDefaultValue());
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("clusterName"), ApolloPropertyKey.CLUSTER_NAME.getDefaultValue());
    FieldSetter.setField(apolloOpenApiWrapper, ApolloOpenApiWrapper.class.getDeclaredField("administrator"), ApolloPropertyKey.ADMINISTRATOR.getDefaultValue());
}
 
Example #19
Source File: PostgreSQLComBindExecutorTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
@SneakyThrows
public void assertExecuteHasError() {
    PostgreSQLComBindExecutor postgreSQLComBindExecutor = new PostgreSQLComBindExecutor(mock(PostgreSQLComBindPacket.class), null);
    FieldSetter.setField(postgreSQLComBindExecutor, PostgreSQLComBindExecutor.class.getDeclaredField("databaseCommunicationEngine"), databaseCommunicationEngine);
    ErrorResponse errorResponse = new ErrorResponse(new PSQLException(mock(ServerErrorMessage.class)));
    when(databaseCommunicationEngine.execute()).thenReturn(errorResponse);
    Assert.assertThat(((LinkedList) postgreSQLComBindExecutor.execute()).get(1), Matchers.instanceOf(PostgreSQLErrorResponsePacket.class));
    Assert.assertThat(postgreSQLComBindExecutor.isErrorResponse(), Matchers.is(true));
}
 
Example #20
Source File: ApolloCenterRepositoryTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@SneakyThrows(ReflectiveOperationException.class)
@BeforeClass
public static void init() {
    CenterConfiguration configuration = new CenterConfiguration("apollo", new Properties());
    configuration.setServerLists("http://config-service-url");
    configuration.setNamespace("orchestration");
    Properties props = new Properties();
    props.setProperty(ApolloPropertyKey.PORTAL_URL.getKey(), PORTAL_URL);
    props.setProperty(ApolloPropertyKey.TOKEN.getKey(), TOKEN);
    REPOSITORY.setProps(props);
    REPOSITORY.init(configuration);
    ApolloConfigWrapper configWrapper = new ApolloConfigWrapper(configuration, new ApolloProperties(props));
    FieldSetter.setField(REPOSITORY, ApolloCenterRepository.class.getDeclaredField("configWrapper"), configWrapper);
    FieldSetter.setField(REPOSITORY, ApolloCenterRepository.class.getDeclaredField("openApiWrapper"), OPEN_API_WRAPPER);
}
 
Example #21
Source File: AnnotationContextManager.java    From AndroidUnitTest with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@NonNull Object target, @NonNull Context context) {
    if (contextField != null) {
        Context appContext = context;
        appContext = Mockito.spy(appContext);
        new FieldSetter(target, this.contextField).set(appContext);
    }
}
 
Example #22
Source File: OverseerTest.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private ZkController createMockZkController(String zkAddress, SolrZkClient zkClient, ZkStateReader reader) throws InterruptedException, NoSuchFieldException, SecurityException, SessionExpiredException {
  ZkController zkController = mock(ZkController.class);

  if (zkClient == null) {
    SolrZkClient newZkClient = new SolrZkClient(server.getZkAddress(), AbstractZkTestCase.TIMEOUT);
    Mockito.doAnswer(
        new Answer<Void>() {
          public Void answer(InvocationOnMock invocation) {
            newZkClient.close();
            return null;
          }}).when(zkController).close();
    zkClient = newZkClient;
  } else {
    doNothing().when(zkController).close();
  }

  CoreContainer mockAlwaysUpCoreContainer = mock(CoreContainer.class,
      Mockito.withSettings().defaultAnswer(Mockito.CALLS_REAL_METHODS));
  when(mockAlwaysUpCoreContainer.isShutDown()).thenReturn(testDone);  // Allow retry on session expiry
  when(mockAlwaysUpCoreContainer.getResourceLoader()).thenReturn(new SolrResourceLoader());
  FieldSetter.setField(zkController, ZkController.class.getDeclaredField("zkClient"), zkClient);
  FieldSetter.setField(zkController, ZkController.class.getDeclaredField("cc"), mockAlwaysUpCoreContainer);
  when(zkController.getCoreContainer()).thenReturn(mockAlwaysUpCoreContainer);
  when(zkController.getZkClient()).thenReturn(zkClient);
  when(zkController.getZkStateReader()).thenReturn(reader);

  when(zkController.getLeaderProps(anyString(), anyString(), anyInt())).thenCallRealMethod();
  when(zkController.getLeaderProps(anyString(), anyString(), anyInt(), anyBoolean())).thenCallRealMethod();
  doReturn(getCloudDataProvider(zkAddress, zkClient, reader))
      .when(zkController).getSolrCloudManager();
  return zkController;
}
 
Example #23
Source File: AISControllerTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #24
Source File: Tcf2ServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void permissionsForShouldNotAllowAllWhenP1TIsFalseAndP1TIIsAccessAllowed() throws NoSuchFieldException {
    // given
    given(bidderCatalog.nameByVendorId(any())).willReturn("rubicon");

    given(tcString.getPurposeOneTreatment()).willReturn(false);

    target = new Tcf2Service(
            GdprConfig.builder()
                    .purposes(purposes)
                    .purposeOneTreatmentInterpretation(PurposeOneTreatmentInterpretation.accessAllowed)
                    .build(),
            vendorListService,
            bidderCatalog);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedPurposeStrategies"), purposeStrategies);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedSpecialFeatureStrategies"), specialFeaturesStrategies);

    // when
    target.permissionsFor(singleton(1), tcString);

    // then
    verify(purposeStrategyOne, never()).allow(any());
    verify(purposeStrategyOne).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyTwo).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategySeven).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyFour).processTypePurposeStrategy(any(), any(), anyCollection());

    verify(specialFeaturesStrategyOne).processSpecialFeaturesStrategy(any(), any(), anyCollection());
}
 
Example #25
Source File: Tcf2ServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void permissionsForShouldAllowAllWhenP1TIIsAccessAllowed() throws NoSuchFieldException {
    // given
    given(bidderCatalog.nameByVendorId(any())).willReturn("rubicon");

    given(tcString.getPurposeOneTreatment()).willReturn(true);

    target = new Tcf2Service(
            GdprConfig.builder()
                    .purposes(purposes)
                    .purposeOneTreatmentInterpretation(PurposeOneTreatmentInterpretation.accessAllowed)
                    .build(),
            vendorListService,
            bidderCatalog);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedPurposeStrategies"), purposeStrategies);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedSpecialFeatureStrategies"), specialFeaturesStrategies);

    // when
    target.permissionsFor(singleton(1), tcString);

    // then
    verify(purposeStrategyOne, never()).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyOne).allow(any());
    verify(purposeStrategyTwo).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategySeven).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyFour).processTypePurposeStrategy(any(), any(), anyCollection());

    verify(specialFeaturesStrategyOne).processSpecialFeaturesStrategy(any(), any(), anyCollection());
}
 
Example #26
Source File: Tcf2ServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void permissionsForShouldReturnAllDeniedWhenP1TIIsNoAccessAllowed() throws NoSuchFieldException {
    // given
    given(bidderCatalog.nameByVendorId(any())).willReturn("rubicon");

    given(tcString.getPurposeOneTreatment()).willReturn(true);

    target = new Tcf2Service(
            GdprConfig.builder()
                    .purposes(purposes)
                    .purposeOneTreatmentInterpretation(PurposeOneTreatmentInterpretation.noAccessAllowed)
                    .build(),
            vendorListService,
            bidderCatalog);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedPurposeStrategies"), purposeStrategies);
    FieldSetter.setField(target,
            target.getClass().getDeclaredField("supportedSpecialFeatureStrategies"), specialFeaturesStrategies);

    // when
    final Future<Collection<VendorPermission>> result = target.permissionsFor(singleton(1), tcString);

    // then
    assertThat(result).succeededWith(
            singletonList(VendorPermission.of(1, "rubicon", PrivacyEnforcementAction.restrictAll())));

    verify(purposeStrategyOne, never()).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyTwo).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategySeven).processTypePurposeStrategy(any(), any(), anyCollection());
    verify(purposeStrategyFour).processTypePurposeStrategy(any(), any(), anyCollection());

    verify(specialFeaturesStrategyOne).processSpecialFeaturesStrategy(any(), any(), anyCollection());
}
 
Example #27
Source File: PisCancellationControllerTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #28
Source File: MaxMindGeoLocationServiceTest.java    From prebid-server-java with Apache License 2.0 5 votes vote down vote up
@Test
public void lookupShouldReturnCountryIsoWhenDatabaseReaderWasSet() throws NoSuchFieldException, IOException,
        GeoIp2Exception {
    // given
    final Country country = new Country(null, null, null, "fr", null);
    final Continent continent = new Continent(null, "eu", null, null);
    final City city = new City(singletonList("test"), null, null, singletonMap("test", "Paris"));
    final Location location = new Location(null, null, 48.8566, 2.3522,
            null, null, null);
    final ArrayList<Subdivision> subdivisions = new ArrayList<>();
    subdivisions.add(new Subdivision(null, null, null, "paris", null));
    final CityResponse cityResponse = new CityResponse(city, continent, country, location, null,
            null, null, null, subdivisions, null);

    final DatabaseReader databaseReader = Mockito.mock(DatabaseReader.class);
    given(databaseReader.city(any())).willReturn(cityResponse);

    FieldSetter.setField(maxMindGeoLocationService,
            maxMindGeoLocationService.getClass().getDeclaredField("databaseReader"), databaseReader);

    // when
    final Future<GeoInfo> future = maxMindGeoLocationService.lookup(TEST_IP, null);

    // then
    assertThat(future.succeeded()).isTrue();
    assertThat(future.result())
            .isEqualTo(GeoInfo.builder()
                    .vendor("maxmind")
                    .continent("eu")
                    .country("fr")
                    .region("paris")
                    .city("Paris")
                    .lat(48.8566f)
                    .lon(2.3522f)
                    .build());
}
 
Example #29
Source File: TestMapNotificationProviderRegistry.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
@Before
public void setup () throws NoSuchFieldException, SecurityException {
    Map<String, NotificationProvider> registryMap = new HashMap<String,NotificationProvider>();
    registryMap.put("LOG", logProvider);
    registryMap.put("WEBHOOK", webhookProvider);

    new FieldSetter(uut, uut.getClass().getDeclaredField("providerRegistry")).set(registryMap);
}
 
Example #30
Source File: AISControllerTest.java    From XS2A-Sandbox with Apache License 2.0 5 votes vote down vote up
@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);
}