Java Code Examples for org.powermock.reflect.Whitebox#setInternalState()

The following examples show how to use org.powermock.reflect.Whitebox#setInternalState() . 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: InAppMessagePrioritizationTest.java    From Leanplum-Android-SDK with Apache License 2.0 6 votes vote down vote up
@Override
public void before() throws Exception {
  super.before();

  mMessageMatchResult = new ActionManager.MessageMatchResult();
  Whitebox.setInternalState(mMessageMatchResult, "matchedTrigger", true);
  Whitebox.setInternalState(mMessageMatchResult, "matchedLimit", true);
  Whitebox.setInternalState(mMessageMatchResult, "matchedActivePeriod", true);
  assertTrue(mMessageMatchResult.matchedTrigger);
  assertTrue(mMessageMatchResult.matchedActivePeriod);
  assertTrue(mMessageMatchResult.matchedLimit);


  mContextualValues = new ActionContext.ContextualValues();
  // create mock object
  mMockActionManager = mock(ActionManager.class);
  // workaround for singleton objects
  Whitebox.setInternalState(ActionManager.class, "instance", mMockActionManager);
}
 
Example 2
Source File: DeepSparkContextTest.java    From deep-spark with Apache License 2.0 6 votes vote down vote up
@Test
public void createJavaSchemaRDDTest() throws Exception {
    deepSparkContext = createDeepSparkContext();
    DeepSparkContext deepSparkContextSpy = PowerMockito.spy(deepSparkContext);
    SQLContext sqlContext = PowerMockito.mock(SQLContext.class);
    ExtractorConfig config = createDeepJobConfig();
    Whitebox.setInternalState(deepSparkContextSpy, "sc", sparkContext);
    Whitebox.setInternalState(deepSparkContextSpy, "sqlContext", sqlContext);
    PowerMockito.doReturn(singleRdd).when(deepSparkContextSpy).createJavaRDD(config);
    JavaRDD<Row> rowRDD = mock(JavaRDD.class);
    mockStatic(DeepSparkContext.class);
    when(DeepSparkContext.createJavaRowRDD(singleRdd)).thenReturn(rowRDD);
    Cells cells = mock(Cells.class);
    when(singleRdd.first()).thenReturn(cells);
    StructType schema = mock(StructType.class);
    mockStatic(CellsUtils.class);
    when(CellsUtils.getStructTypeFromCells(cells)).thenReturn(schema);

    deepSparkContextSpy.createJavaSchemaRDD(config);

    verify(sqlContext).applySchema(rowRDD, schema);
}
 
Example 3
Source File: Test_LocalFileSystemOperations.java    From ats-framework with Apache License 2.0 6 votes vote down vote up
@Test
public void createBinaryFilePositiveRandomContent() throws IOException {

    //Replace the randomGenerator with cutsom one.
    Random random = new Random(1);
    Random originalRandom = (Random) Whitebox.getInternalState(testObject.getClass(),
                                                               "randomGenerator");
    Whitebox.setInternalState(testObject.getClass(), "randomGenerator", random);

    testObject.createBinaryFile(file.getPath(), 10, true);

    //Restore original random generator
    Whitebox.setInternalState(testObject.getClass(), "randomGenerator", originalRandom);

    assertTrue(file.exists());
    assertEquals(10L, file.length());

    byte[] expectedBytes = new byte[]{ 115, -40, 111, -110, -4, -16, -27, -35, -43, 104 };
    byte[] actualBytes = new byte[10];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    bis.read(actualBytes);
    assertTrue(Arrays.equals(expectedBytes, actualBytes));
    bis.close();

}
 
Example 4
Source File: ObjectStoreFileSystemTest.java    From stocator with Apache License 2.0 6 votes vote down vote up
@Test
public void deleteTest() throws Exception {
  Assume.assumeNotNull(getFs());

  Path testFile = new Path(getBaseURI() + "/testFile");
  createFile(testFile, data);
  Path input = new Path(getBaseURI() + "/a/b/c/m.data/_temporary/"
          + "0/_temporary/attempt_201603141928_0000_m_000099_102/part-00099");
  Whitebox.setInternalState(mMockObjectStoreFileSystem, "hostNameScheme", getBaseURI());
  String result = Whitebox.invokeMethod(mMockStocatorPath, "parseHadoopFOutputCommitterV1", input,
      true, getBaseURI());
  Path modifiedInput = new Path(getBaseURI() + result);
  createFile(input, data);
  Assert.assertTrue(getFs().exists(modifiedInput));
  Assert.assertTrue(getFs().exists(testFile));

  getFs().delete(testFile, false);
  Assert.assertFalse(getFs().exists(testFile));

  getFs().delete(modifiedInput, false);
  Assert.assertFalse(getFs().exists(modifiedInput));
}
 
Example 5
Source File: ClusterModuleConsulProviderTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Test
public void prepareSingle() throws Exception {
    ClusterModuleConsulConfig consulConfig = new ClusterModuleConsulConfig();
    consulConfig.setHostPort("10.0.0.1:1000");
    Whitebox.setInternalState(provider, "config", consulConfig);

    Consul consulClient = mock(Consul.class);
    Consul.Builder builder = mock(Consul.Builder.class);
    when(builder.build()).thenReturn(consulClient);

    PowerMockito.mockStatic(Consul.class);
    when(Consul.builder()).thenReturn(builder);
    when(builder.withConnectTimeoutMillis(anyLong())).thenCallRealMethod();

    when(builder.withHostAndPort(any())).thenReturn(builder);

    provider.prepare();

    ArgumentCaptor<HostAndPort> hostAndPortArgumentCaptor = ArgumentCaptor.forClass(HostAndPort.class);
    verify(builder).withHostAndPort(hostAndPortArgumentCaptor.capture());

    HostAndPort address = hostAndPortArgumentCaptor.getValue();
    assertEquals(HostAndPort.fromParts("10.0.0.1", 1000), address);
}
 
Example 6
Source File: PullMessageFilterChainTest.java    From qmq with Apache License 2.0 5 votes vote down vote up
/**
 * filter 启用但不匹配, 此时消息被丢弃
 */
@Test
public void testPullOnFilterActiveNotMatch() throws Exception {
	Whitebox.setInternalState(pullMessageFilterChain, "filters", Lists.newArrayList(activeNotMatchFilter));
	PullRequest request = TestToolBox.createDefaultPullRequest();
	Buffer buffer = TestToolBox.createDefaultBuffer();
	boolean needKeep = pullMessageFilterChain.needKeep(request, buffer);
	assertFalse(needKeep);
}
 
Example 7
Source File: EnvPullMessageFilterTest.java    From qmq with Apache License 2.0 5 votes vote down vote up
/**
 * 测试开关打开但 filter 存在的情况
 */
@Test
public void testInactiveOnSwitchOnButFilterExists() {
	Buffer buffer = TestToolBox.createDefaultBuffer();
	PullRequest request = TestToolBox.createDefaultPullRequest();
	request.setFilters(Lists.newArrayList(new SubEnvIsolationPullFilter("test", "test")));
	EnvPullMessageFilter filter = Mockito.spy(EnvPullMessageFilter.class);
	Whitebox.setInternalState(filter, "enableSubEnvIsolation", true);
	boolean active = filter.isActive(request, buffer);
	assertTrue(active);
}
 
Example 8
Source File: BaseViewModelTest.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setup() {
    super.setup();
    // noinspection unchecked
    stateLiveData = mock(SafeMutableLiveData.class);
    mNavigatorHelper = mock(NavigatorHelper.class);
    Whitebox.setInternalState(viewModel, "stateLiveData", stateLiveData);
    Whitebox.setInternalState(viewModel, "navigatorHelper", mNavigatorHelper);
}
 
Example 9
Source File: TestBigQueryTarget.java    From datacollector with Apache License 2.0 5 votes vote down vote up
private TargetRunner createAndRunner(BigQueryTargetConfig config, List<Record> records) throws Exception {
  Target target = new BigQueryTarget(config);
  TargetRunner runner = new TargetRunner.Builder(BigQueryDTarget.class, target)
      .setOnRecordError(OnRecordError.TO_ERROR)
      .build();
  runner.runInit();
  Whitebox.setInternalState(target, "bigQuery", bigQuery);
  try {
    runner.runWrite(records);
  } finally {
    runner.runDestroy();
  }
  return runner;
}
 
Example 10
Source File: ScriptValuesMetaModTest.java    From hop with Apache License 2.0 5 votes vote down vote up
@Test
public void testExtend() {
  ScriptValuesMetaMod meta = new ScriptValuesMetaMod();
  int size = 1;
  meta.extend( size );

  Assert.assertEquals( size, meta.getFieldname().length );
  Assert.assertNull( meta.getFieldname()[ 0 ] );
  Assert.assertEquals( size, meta.getRename().length );
  Assert.assertNull( meta.getRename()[ 0 ] );
  Assert.assertEquals( size, meta.getType().length );
  Assert.assertEquals( -1, meta.getType()[ 0 ] );
  Assert.assertEquals( size, meta.getLength().length );
  Assert.assertEquals( -1, meta.getLength()[ 0 ] );
  Assert.assertEquals( size, meta.getPrecision().length );
  Assert.assertEquals( -1, meta.getPrecision()[ 0 ] );
  Assert.assertEquals( size, meta.getReplace().length );
  Assert.assertFalse( meta.getReplace()[ 0 ] );

  meta = new ScriptValuesMetaMod();
  // set some values, uneven lengths
  Whitebox.setInternalState( meta, "fieldname", new String[] { "Field 1", "Field 2", "Field 3" } );
  Whitebox.setInternalState( meta, "rename", new String[] { "Field 1 - new" } );
  Whitebox.setInternalState( meta, "type", new int[] { IValueMeta.TYPE_STRING, IValueMeta
    .TYPE_INTEGER, IValueMeta.TYPE_NUMBER } );

  meta.extend( 3 );
  validateExtended( meta );
}
 
Example 11
Source File: IdentityUtilTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "getOperationCleanUpPeriodData")
public void testGetOperationCleanUpPeriod(String value, long expected) throws Exception {
    Map<String, Object> mockConfiguration = new HashMap<>();
    mockConfiguration.put(IdentityConstants.ServerConfig.OPERATION_CLEAN_UP_PERIOD, value);
    Whitebox.setInternalState(IdentityUtil.class, "configuration", mockConfiguration);
    assertEquals(IdentityUtil.getOperationCleanUpPeriod("IgnoredParam"), expected, "Expected value mismatches " +
            "returned for input: " + value);
}
 
Example 12
Source File: IdentityUtilTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider = "getPropertyTestData")
public void testGetProperty(String key, Object value, String expected) throws Exception {
    Map<String, Object> mockConfig = new HashMap<>();
    mockConfig.put(key, value);

    Whitebox.setInternalState(IdentityUtil.class, "configuration", mockConfig);
    assertEquals(IdentityUtil.getProperty(key), expected, String.format("Property value mismatch for input: key " +
            "= %s, value = %s", key, String.valueOf(value)));
}
 
Example 13
Source File: IdentityUtilTest.java    From carbon-identity-framework with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetIdentityCookieConfig() throws Exception {
    Map<String, IdentityCookieConfig> mockIdentityCookiesConfigurationHolder = new HashMap<>();
    IdentityCookieConfig cookieConfig = new IdentityCookieConfig("cookieName");
    mockIdentityCookiesConfigurationHolder.put("cookie", cookieConfig);
    Whitebox.setInternalState(IdentityUtil.class, "identityCookiesConfigurationHolder",
            mockIdentityCookiesConfigurationHolder);
    assertEquals(IdentityUtil.getIdentityCookieConfig("cookie"), cookieConfig, "Invalid cookie config value " +
            "for: cookie");
    assertNull(IdentityUtil.getIdentityCookieConfig("nonExisting"), "Non existing cookie key should be returned " +
            "with null");

}
 
Example 14
Source File: EncrypterUtilEncryptionTest.java    From SMSC with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalStateException.class)
public void testDecryptObjectWithOtherSecretKey() throws Exception {
    EncrypterUtil.encrypt(obj1);

    Whitebox.setInternalState(EncrypterUtil.class, "fake");

    EncrypterUtil.decrypt(obj1);
}
 
Example 15
Source File: AppComponentInjector.java    From friendly-plans with GNU General Public License v3.0 4 votes vote down vote up
public static void injectIntoApp(AppComponent appComponent) {
    final App application = (App) RuntimeEnvironment.application;
    Whitebox.setInternalState(application, "appComponent", appComponent);
}
 
Example 16
Source File: ModuleSpecTest.java    From react-native-GPay with MIT License 4 votes vote down vote up
@Test
public void testSimpleDefaultConstructor() {
  Whitebox.setInternalState(ReactBuildConfig.class, "DEBUG", true);
  ModuleSpec spec = ModuleSpec.simple(SimpleModule.class);
  assertThat(spec.getProvider().get()).isInstanceOf(SimpleModule.class);
}
 
Example 17
Source File: DbUpgradeUtilsTest.java    From cloudstack with Apache License 2.0 4 votes vote down vote up
@Before
public void setupClass() {
    Whitebox.setInternalState(DbUpgradeUtils.class, "dao", daoMock);
}
 
Example 18
Source File: SQLConstantmanagerFactoryTestCase.java    From carbon-apimgt with Apache License 2.0 4 votes vote down vote up
@Test(expected = APIManagementException.class)
public void testGetSQLStringNoDBTypeFound() throws Exception{
    Whitebox.setInternalState(SQLConstantManagerFactory.class, "dbType", "");
    SQLConstantManagerFactory.getSQlString("");
}
 
Example 19
Source File: AppServletContextListenerTest.java    From aws-mock with MIT License 4 votes vote down vote up
@Test
public void Test_contextInitializedPersistenceEnabled() {
    Whitebox.setInternalState(AppServletContextListener.class, "persistenceEnabled", true);
    acl.contextInitialized(sce);
    Whitebox.setInternalState(AppServletContextListener.class, "persistenceEnabled", false);
}
 
Example 20
Source File: WrapperContextListenerTest.java    From scheduling with GNU Affero General Public License v3.0 4 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    mockStarter = PowerMockito.mock(WarWrapper.class);
    Whitebox.setInternalState(WarWrapper.class, "INSTANCE", mockStarter);
}