org.junit.jupiter.api.DynamicNode#org.springframework.test.util.ReflectionTestUtils源码实例Demo

下面列出了org.junit.jupiter.api.DynamicNode#org.springframework.test.util.ReflectionTestUtils 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: cosmic   文件: AccountManagerImplTest.java
@Before
public void setup() throws NoSuchFieldException, SecurityException,
        IllegalArgumentException, IllegalAccessException {
    accountManager = new AccountManagerImpl();
    for (final Field field : AccountManagerImpl.class.getDeclaredFields()) {
        if (field.getAnnotation(Inject.class) != null) {
            field.setAccessible(true);
            try {
                final Field mockField = this.getClass().getDeclaredField(
                        field.getName());
                field.set(accountManager, mockField.get(this));
            } catch (final Exception e) {
                // ignore missing fields
            }
        }
    }
    ReflectionTestUtils.setField(accountManager, "_userAuthenticators", Arrays.asList(userAuthenticator));
    accountManager.setSecurityCheckers(Arrays.asList(securityChecker));
    CallContext.register(callingUser, callingAccount);
}
 
@Test
public void testAuthenticateJwt() {
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    ZosmfService zosmfService = mock(ZosmfService.class);
    ZosmfAuthenticationProvider zosmfAuthenticationProvider = new ZosmfAuthenticationProvider(authenticationService, zosmfService);
    ReflectionTestUtils.setField(zosmfAuthenticationProvider, "useJwtToken", Boolean.TRUE);
    Authentication authentication = mock(Authentication.class);
    when(authentication.getPrincipal()).thenReturn("user1");
    TokenAuthentication authentication2 = mock(TokenAuthentication.class);

    when(zosmfService.authenticate(authentication)).thenReturn(new ZosmfService.AuthenticationResponse(
        "domain1",
        Collections.singletonMap(ZosmfService.TokenType.JWT, "jwtToken1")
    ));
    when(authenticationService.createTokenAuthentication("user1", "jwtToken1")).thenReturn(authentication2);

    assertSame(authentication2, zosmfAuthenticationProvider.authenticate(authentication));
}
 
源代码3 项目: pacbot   文件: AssetServiceTest.java
@Test
public void testgetAssetGroupInfo() throws Exception {

    Map<String, Object> agMap1 = new HashMap<>();
    agMap1.put("name", "testDomain");

    List<Map<String, Object>> agList = new ArrayList<>();
    agList.add(agMap1);

    when(assetRepository.getAssetGroupInfo(anyString())).thenReturn(agMap1);
    when(assetRepository.getApplicationByAssetGroup(anyString())).thenReturn(Arrays.asList("pacman", "monitor"));
    ReflectionTestUtils.setField(service, "repository", assetRepository);

    Map<String, Object> a = service.getAssetGroupInfo("testAg");
    System.out.println(a);
    assertTrue(a.size() == 4);

}
 
源代码4 项目: pacbot   文件: AssetControllerTest.java
@Test
public void testgetAssetGroupInfo() throws Exception {
    List<Map<String, Object>> tTypeList = new ArrayList<>();
    Map<String, Object> tTypeMap = new HashMap<>();
    
    when(service.getAssetGroupInfo("ag")).thenReturn(tTypeMap);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj0 = controller.getAssetGroupInfo("ag");
    assertTrue(responseObj0.getStatusCode() == HttpStatus.EXPECTATION_FAILED);
    
    tTypeMap.put("name", "aws-all");
    tTypeList.add(tTypeMap);

    when(service.getAssetGroupInfo("ag")).thenReturn(tTypeMap);
    ReflectionTestUtils.setField(controller, "assetService", service);

    ResponseEntity<Object> responseObj = controller.getAssetGroupInfo("ag");
    assertTrue(responseObj.getStatusCode() == HttpStatus.OK);
    assertTrue(((Map<String, Object>) responseObj.getBody()).get("data") != null);
}
 
@Test
public void testDefaultConfiguration() {
	this.context = new AnnotationConfigServletWebServerApplicationContext();
	this.context.register(AuthorizationAndResourceServerConfiguration.class, MinimalSecureWebApplication.class);
	this.context.refresh();
	this.context.getBean(AUTHORIZATION_SERVER_CONFIG);
	this.context.getBean(RESOURCE_SERVER_CONFIG);
	this.context.getBean(OAuth2MethodSecurityConfiguration.class);
	ClientDetails config = this.context.getBean(BaseClientDetails.class);
	AuthorizationEndpoint endpoint = this.context.getBean(AuthorizationEndpoint.class);
	UserApprovalHandler handler = (UserApprovalHandler) ReflectionTestUtils.getField(endpoint,
			"userApprovalHandler");
	ClientDetailsService clientDetailsService = this.context.getBean(ClientDetailsService.class);
	ClientDetails clientDetails = clientDetailsService.loadClientByClientId(config.getClientId());
	assertThat(AopUtils.isJdkDynamicProxy(clientDetailsService)).isTrue();
	assertThat(AopUtils.getTargetClass(clientDetailsService).getName())
			.isEqualTo(InMemoryClientDetailsService.class.getName());
	assertThat(handler).isInstanceOf(ApprovalStoreUserApprovalHandler.class);
	assertThat(clientDetails).isEqualTo(config);
	verifyAuthentication(config);
	assertThat(this.context.getBeanNamesForType(OAuth2RestOperations.class)).isEmpty();
}
 
源代码6 项目: pmq   文件: ConsumerCommitServiceImplTest.java
@Before
public void init() {
	consumerCommitServiceImpl = new ConsumerCommitServiceImpl();
	queueOffsetService = mock(QueueOffsetService.class);
	SoaConfig soaConfig = new SoaConfig();
	Environment env = mock(Environment.class);
	ReflectionTestUtils.setField(soaConfig, "env", env);
	ReflectionTestUtils.setField(consumerCommitServiceImpl, "queueOffsetService", queueOffsetService);
	ReflectionTestUtils.setField(consumerCommitServiceImpl, "soaConfig", soaConfig);
	when(env.getProperty(anyString(), anyString())).thenAnswer(new Answer<String>() {
		@Override
		public String answer(InvocationOnMock invocation) throws Throwable {
			Object[] args = invocation.getArguments();
			return (String) args[1];
		}
	});
}
 
源代码7 项目: pacbot   文件: CertificateRepositoryTest.java
@Test
public void getCerticatesSummaryTest_Exception() throws Exception {
    
    when(complianceRepository.getCertificates(anyString())).thenReturn(new HashMap<>());
    ReflectionTestUtils.setField(certificateRepository, "complianceRepository", complianceRepository);
    mockStatic(PacHttpUtils.class);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
    ReflectionTestUtils.setField(certificateRepository, "esUrl", "dummyEsURL");
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesSummary("ag"))
    .isInstanceOf(DataException.class);
    
    when(complianceRepository.getCertificates(anyString())).thenThrow(new DataException());
    ReflectionTestUtils.setField(certificateRepository, "complianceRepository", complianceRepository);
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesSummary("ag"))
    .isInstanceOf(DataException.class);
}
 
源代码8 项目: pacbot   文件: AssetListControllerTest.java
@Test
public void testgetEditableFieldsByTargetType() throws Exception{
    ResponseEntity<Object> responseObj1 = controller.getEditableFieldsByTargetType("","ec2");
    assertTrue(responseObj1.getStatusCode()==HttpStatus.EXPECTATION_FAILED);
   
    List<Map<String, Object>> aList = new ArrayList<>();
    Map<String,Object> aMap = new HashMap<>();
    aMap.put("type", "ec2");
    aList.add(aMap);
    
    when(service.getTargetTypesForAssetGroup(anyString(),anyString(),anyString())).thenReturn(aList);
    ReflectionTestUtils.setField(controller, "assetService", service);
    ResponseEntity<Object> responseObj2 = controller.getEditableFieldsByTargetType("ag","ec2");
    assertTrue(responseObj2.getStatusCode()==HttpStatus.OK);
    
    ResponseEntity<Object> responseObj3 = controller.getEditableFieldsByTargetType("ag","s3");
    assertTrue(responseObj3.getStatusCode()==HttpStatus.EXPECTATION_FAILED);
  
}
 
@Test
public void testCustomizeServletContainer() {
    env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
    UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
    webConfigurer.customize(container);
    assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
    assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
    assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    if (container.getDocumentRoot() != null) {
        assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("target/www"));
    }

    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
 
@Test(expected = DocumentCryptException.class)
@DirtiesContext
public void checkWrongKeyRoot() {
    // save to db, version = 0
    MyBean bean = new MyBean();
    bean.secretString = "secret";
    bean.nonSensitiveData = getClass().getSimpleName();
    mongoTemplate.insert(bean);

    // override version 0's key
    ReflectionTestUtils.setField(cryptVault, "cryptVersions", new CryptVersion[256]);
    cryptVault.with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, Base64.getDecoder().decode("aic7QGYCCSHyy7gYRCyNTpPThbomw1/dtWl4bocyTnU="));

    try {
        mongoTemplate.find(query(where(MONGO_NONSENSITIVEDATA).is(getClass().getSimpleName())), MyBean.class);
    } catch (DocumentCryptException e) {
        assertCryptException(e, "mybean", null, "secretString");
        throw e;
    }
}
 
源代码11 项目: pacbot   文件: ESManagerTest.java
@SuppressWarnings({ "unchecked", "static-access" })
@Test 
public void deleteOldDocumentsTest() throws Exception{
    
    HttpEntity jsonEntity = new StringEntity("{}", ContentType.APPLICATION_JSON);
    when(response.getEntity()).thenReturn(jsonEntity);
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenReturn(response);
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    
    esManager.deleteOldDocuments("index", "type", "field","value");
    
    when(restClient.performRequest(anyString(), anyString(), anyMap(), any(HttpEntity.class),
    Matchers.<Header>anyVararg())).thenThrow(new IOException());
    ReflectionTestUtils.setField(esManager, "restClient", restClient);
    esManager.deleteOldDocuments("index", "type", "field","value");
}
 
@Test(expected = DocumentCryptException.class)
@DirtiesContext
public void checkWrongKeyCustomId() {
    // save to db, version = 0
    MyBean bean = new MyBean();
    bean.id = "customId";
    bean.secretString = "secret";
    bean.nonSensitiveData = getClass().getSimpleName();
    mongoTemplate.insert(bean);

    // override version 0's key
    ReflectionTestUtils.setField(cryptVault, "cryptVersions", new CryptVersion[256]);
    cryptVault.with256BitAesCbcPkcs5PaddingAnd128BitSaltKey(0, Base64.getDecoder().decode("aic7QGYCCSHyy7gYRCyNTpPThbomw1/dtWl4bocyTnU="));

    try {
        mongoTemplate.find(query(where(MONGO_NONSENSITIVEDATA).is(getClass().getSimpleName())), MyBean.class);
    } catch (DocumentCryptException e) {
        assertCryptException(e, "mybean", null, "secretString");
        throw e;
    }
}
 
源代码13 项目: x-pipe   文件: KeeperContainerServiceTest.java
@Before
public void setUp() throws Exception {
    keeperContainerService = new KeeperContainerService();

    ReflectionTestUtils.setField(keeperContainerService, "leaderElectorManager", leaderElectorManager);
    ReflectionTestUtils.setField(keeperContainerService, "leaderElectorManager", leaderElectorManager);
    ReflectionTestUtils.setField(keeperContainerService, "keeperContainerConfig", keeperContainerConfig);
    ReflectionTestUtils.setField(keeperContainerService, "keeperConfig", keeperConfig);
    ReflectionTestUtils.setField(keeperContainerService, "keepersMonitorManager", keepersMonitorManager);

    someCluster = "someCluster";
    someShard = "someShard";
    somePort = 6789;

    someKeeperMeta = new KeeperMeta();
    someKeeperMeta.setPort(somePort);
    someKeeperTransMeta = new KeeperTransMeta();
    someKeeperTransMeta.setClusterId(someCluster);
    someKeeperTransMeta.setShardId(someShard);
    someKeeperTransMeta.setKeeperMeta(someKeeperMeta);

    when(keeperContainerConfig.getReplicationStoreDir()).thenReturn(System.getProperty("user.dir"));

    ReflectionTestUtils.setField(ComponentRegistryHolder.class, "componentRegistry", componentRegistry);
}
 
@Test
public void testCustomizeServletContainer() {
    env.setActiveProfiles(JHipsterConstants.SPRING_PROFILE_PRODUCTION);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    assertThat(container.getMimeMappings().get("abs")).isEqualTo("audio/x-mpeg");
    assertThat(container.getMimeMappings().get("html")).isEqualTo("text/html;charset=utf-8");
    assertThat(container.getMimeMappings().get("json")).isEqualTo("text/html;charset=utf-8");
    if (container.getDocumentRoot() != null) {
        assertThat(container.getDocumentRoot().getPath()).isEqualTo(FilenameUtils.separatorsToSystem("build/www"));
    }

    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isNull();
}
 
源代码15 项目: pacbot   文件: ComplianceRepositoryImplTest.java
@Test
public void updateKernelVersionTest() throws Exception {
    KernelVersion kernelVersion = new KernelVersion();
    kernelVersion.setInstanceId("12345");
    kernelVersion.setKernelVersionId("12345");
    String response = "{\"count\":0,\"_shards\":{\"total\":3,\"successful\":3,\"failed\":0}}";
    String responsewithcount = "{\"count\":10,\"_shards\":{\"total\":3,\"successful\":3,\"failed\":0}}";
    ReflectionTestUtils.setField(complianceRepositoryImpl, "esUrl", "dummyEsURL");
    String kernelCriteria = "el6.x#2.6333.32-696.23.1.el6.x86_64|el7#3.10.0-6933333.231.1.el7.x86_64|el6uek#3.8.13-133318.20.3.el6uek-x86_64|amzn1#4.9.85-38.55558.amzn1.x86_64";

    when(rdsepository.queryForString(anyString())).thenReturn(kernelCriteria);
    mockStatic(PacHttpUtils.class);

    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(responsewithcount);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);

    RhnSystemDetails systemDetails = new RhnSystemDetails();
    systemDetails.setCompanyId(123l);
    when(rhnSystemDetailsRepository.findRhnSystemDetailsByInstanceId(kernelVersion.getInstanceId())).thenReturn(
            systemDetails);
    complianceRepositoryImpl.updateKernelVersion(kernelVersion);
    KernelVersion emptyKernalVersion = new KernelVersion();
    complianceRepositoryImpl.updateKernelVersion(emptyKernalVersion);
}
 
@Before
public void individualTestSetup() throws IOException {
  // Wiremock stubs
  stubFor(
      post("/session")
          .willReturn(
              ok(
                  "{\"value\":{\"capabilities\":{\"desired\":{\"platformName\":\"android\",\"app\":\"test.apk\",\"appActivity\":\"test\",\"appPackage\":\"test\"},\"platformName\":\"android\",\"app\":\"test.apk\",\"appActivity\":\"test\",\"appPackage\":\"test\",\"deviceName\":\"Google Pixel\"},\"sessionId\":\"sessionId\"}}")));
  stubFor(post("/upload").willReturn(ok("{app_url : \"test.apk\"}")));

  // Spring config values
  ReflectionTestUtils.setField(target, "username", "user");
  ReflectionTestUtils.setField(target, "accessKey", "key");
  ReflectionTestUtils.setField(
      target,
      "appPath",
      new DefaultResourceLoader().getResource("test.apk").getFile().getAbsolutePath());
  ReflectionTestUtils.setField(
      target, "uploadPath", "http://localhost:" + wireMockPort + "/upload");

  // Mock URL builder
  BrowserStackUrlBuilder mockUrlBuilder = mock(BrowserStackUrlBuilder.class);
  when(mockUrlBuilder.buildBrowserStackUrl(anyString(), anyString()))
      .thenReturn(new URL("http://localhost:" + wireMockPort));
  ReflectionTestUtils.setField(target, "browserStackUrlBuilder", mockUrlBuilder);
}
 
源代码17 项目: sdn-rx   文件: Neo4jDataAutoConfigurationTest.java
@Test
@DisplayName("…should create new Neo4j Template")
void shouldCreateNew() {
	contextRunner
		.withUserConfiguration(ConfigurationWithExistingDatabaseSelectionProvider.class)
		.run(ctx -> {
			assertThat(ctx).hasSingleBean(Neo4jTemplate.class);

			// Verify that the template uses the provided database name provider
			Neo4jTemplate template = ctx.getBean(Neo4jTemplate.class);
			DatabaseSelectionProvider provider = (DatabaseSelectionProvider) ReflectionTestUtils
				.getField(template, "databaseSelectionProvider");
			assertThat(provider).isSameAs(ctx.getBean(DatabaseSelectionProvider.class));
		});
}
 
源代码18 项目: pacbot   文件: VulnerabilityRepositoryTest.java
@Test
public void getTrendAnnotationsTest_Exception() throws Exception {

	mockStatic(PacHttpUtils.class);
	when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
	ReflectionTestUtils.setField(vulnerabilityRepository, "esUrl", "dummyEsURL");

	assertTrue(vulnerabilityRepository.getTrendAnnotations("ag", new Date()).size() == 0);
}
 
源代码19 项目: gpmr   文件: UserResourceIntTest.java
@Before
public void setup() {
    UserResource userResource = new UserResource();
    ReflectionTestUtils.setField(userResource, "userRepository", userRepository);
    ReflectionTestUtils.setField(userResource, "userService", userService);
    this.restUserMockMvc = MockMvcBuilders.standaloneSetup(userResource).build();
}
 
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Map<String, Person> relatives = newPerson.getRelatives();

	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	relatives.put("RELATIVE_1", d);

	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	relatives.put("RELATIVE_2", d);

	newPerson = repository.save(newPerson);
	relatives = newPerson.getRelatives();
	assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
			+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
			+ "RETURN size((t)-->(:Person))"
			+ " as numberOfRelations", Values.parameters("id", newPerson.getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
源代码21 项目: pacbot   文件: VulnerabilityRepositoryTest.java
@Test
public void getVulnerabilityByQidTest() throws Exception {

	String response = "{\"hits\":{\"total\":68,\"hits\":[{\"_index\":\"qualys-kb\",\"_type\":\"kb\",\"_id\":\"236591\",\"_score\":8.899231,"
			+ "\"_source\":{\"qid\":\"236591\",\"vulntype\":\"Vulnerability\",\"severitylevel\":4,\"title\":\"Red Hat Update for kernel\","
			+ "\"category\":\"RedHat\",\"lastservicemodificationdatetime\":\"2018-05-29T20:32:16z\",\"publisheddatetime\":\"2018-01-04T04:02:43z\","
			+ "\"_loadDate\":\"2018-07-09T14:23:27z\",\"latest\":true,\"classification\":\"OS\"}}]}}";

	mockStatic(PacHttpUtils.class);
	when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenReturn(response);
	ReflectionTestUtils.setField(vulnerabilityRepository, "esUrl", "dummyEsURL");

	assertThat(vulnerabilityRepository.getVulnerabilityByQid("qid"), is(notNullValue()));
}
 
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowEmbeddedServletContainerFactory container = new UndertowEmbeddedServletContainerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
源代码24 项目: pacbot   文件: CertificateRepositoryTest.java
@Test
public void getCerticatesExpiryByApplicationTest_Exception() throws Exception {
    
    mockStatic(PacHttpUtils.class);
    when(PacHttpUtils.doHttpPost(anyString(), anyString())).thenThrow(new Exception());
    ReflectionTestUtils.setField(certificateRepository, "esUrl", "dummyEsURL");
    
    assertThatThrownBy(() -> certificateRepository.getCertificatesExpiryByApplication("ag"))
    .isInstanceOf(DataException.class);
}
 
@Test
void shouldWriteDynamicRelationships(@Autowired PersonWithRelativesRepository repository) {

	PersonWithStringlyTypedRelatives newPerson = new PersonWithStringlyTypedRelatives("Test");
	Person d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R1");
	newPerson.getRelatives().put("RELATIVE_1", d);
	d = new Person();
	ReflectionTestUtils.setField(d, "firstName", "R2");
	newPerson.getRelatives().put("RELATIVE_2", d);

	List<PersonWithStringlyTypedRelatives> recorded = new ArrayList<>();
	repository.save(newPerson)
		.as(StepVerifier::create)
		.recordWith(() -> recorded)
		.consumeNextWith(personWithRelatives -> {
			Map<String, Person> relatives = personWithRelatives.getRelatives();
			assertThat(relatives).containsOnlyKeys("RELATIVE_1", "RELATIVE_2");
		})
		.verifyComplete();

	try (Transaction transaction = driver.session().beginTransaction()) {
		long numberOfRelations = transaction.run(""
				+ "MATCH (t:" + labelOfTestSubject + ") WHERE id(t) = $id "
				+ "RETURN size((t)-->(:Person))"
				+ " as numberOfRelations",
			Values.parameters("id", recorded.get(0).getId()))
			.single().get("numberOfRelations").asLong();
		assertThat(numberOfRelations).isEqualTo(2L);
	}
}
 
@Before
public void setup() {
    JHipsterProperties jHipsterProperties = new JHipsterProperties();
    tokenProvider = new TokenProvider(jHipsterProperties);
    ReflectionTestUtils.setField(tokenProvider, "secretKey", "test secret");
    ReflectionTestUtils.setField(tokenProvider, "tokenValidityInMilliseconds", 60000);
    jwtFilter = new JWTFilter(tokenProvider);
    SecurityContextHolder.getContext().setAuthentication(null);
}
 
@Before
public void init() {
  hiveConf.setVar(ConfVars.METASTOREURIS, "thrift://localhost:123");
  client = new ThriftMetastoreClientManager(hiveConf, hiveCompatibleThriftHiveMetastoreIfaceFactory,
      connectionTimeout);
  ReflectionTestUtils.setField(client, "transport", transport);
  ReflectionTestUtils.setField(client, "isConnected", true);
}
 
@SuppressWarnings("unchecked")
private static void assertCacheContents(DefaultContextCache cache, String... expectedNames) {

	Map<MergedContextConfiguration, ApplicationContext> contextMap =
			(Map<MergedContextConfiguration, ApplicationContext>) ReflectionTestUtils.getField(cache, "contextMap");

	// @formatter:off
	List<String> actualNames = contextMap.keySet().stream()
		.map(cfg -> cfg.getClasses()[0])
		.map(Class::getSimpleName)
		.collect(toList());
	// @formatter:on

	assertEquals(asList(expectedNames), actualNames);
}
 
@Test
public void testUndertowHttp2Enabled() {
    props.getHttp().setVersion(JHipsterProperties.Http.Version.V_2_0);
    UndertowServletWebServerFactory container = new UndertowServletWebServerFactory();
    webConfigurer.customize(container);
    Builder builder = Undertow.builder();
    container.getBuilderCustomizers().forEach(c -> c.customize(builder));
    OptionMap.Builder serverOptions = (OptionMap.Builder) ReflectionTestUtils.getField(builder, "serverOptions");
    assertThat(serverOptions.getMap().get(UndertowOptions.ENABLE_HTTP2)).isTrue();
}
 
源代码30 项目: pmq   文件: AuditLogServiceImplTest.java
@Test
public void insertTest() {
	AuditLogServiceImpl auditLogServiceImpl=new AuditLogServiceImpl();
	UserInfoHolder userInfoHolder=mock(UserInfoHolder.class);
	AuditLogRepository auditLogRepository=mock(AuditLogRepository.class);
	ReflectionTestUtils.setField(auditLogServiceImpl, "userInfoHolder", userInfoHolder);
	ReflectionTestUtils.setField(auditLogServiceImpl, "auditLogRepository", auditLogRepository);
	auditLogServiceImpl.init();
	AuditLogEntity entity=new AuditLogEntity();
	entity.setContent("test");
	entity.setId(1L);
	entity.setRefId(1L);
	auditLogServiceImpl.insert(entity);
	verify(auditLogRepository).insert(entity);
}