Java Code Examples for org.powermock.api.mockito.PowerMockito#mockStatic()

The following examples show how to use org.powermock.api.mockito.PowerMockito#mockStatic() . 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: RNInstabugBugReportingModuleTest.java    From Instabug-React-Native with MIT License 6 votes vote down vote up
@Test
public void givenArgs$showBugReportingWithReportTypeAndOptions_whenQuery_thenShouldCallNativeApiWithEnums() {
    // given
    PowerMockito.mockStatic(BugReporting.class);
    final Map<String, Object> optionsArgs = new HashMap<>();
    final Map<String, Object> reportTypeArgs = new HashMap<>();
    ArgsRegistry.registerInvocationOptionsArgs(optionsArgs);
    ArgsRegistry.registerInstabugReportTypesArgs(reportTypeArgs);
    final String[] keysArray = optionsArgs.keySet().toArray(new String[0]);
    final String[] reportTypeKeys = reportTypeArgs.keySet().toArray(new String[0]);
    JavaOnlyArray actualArray = new JavaOnlyArray();
    actualArray.pushString(keysArray[0]);
    actualArray.pushString(keysArray[1]);
    // when
    bugReportingModule.show(reportTypeKeys[0], actualArray);
    // then
    int option1 = (int) optionsArgs.get(keysArray[0]);
    int option2 = (int) optionsArgs.get(keysArray[1]);
    PowerMockito.verifyStatic(VerificationModeFactory.times(1));
    BugReporting.setOptions(option1);
    PowerMockito.verifyStatic(VerificationModeFactory.times(1));
    BugReporting.setOptions(option2);
    PowerMockito.verifyStatic(VerificationModeFactory.times(1));
    BugReporting.show((int) reportTypeArgs.get(reportTypeKeys[0]));
}
 
Example 2
Source File: GetIssueLinkStepTest.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {

  // Prepare site.
  when(envVarsMock.get("JIRA_SITE")).thenReturn("LOCAL");
  when(envVarsMock.get("BUILD_URL")).thenReturn("http://localhost:8080/jira-testing/job/01");

  PowerMockito.mockStatic(Site.class);
  Mockito.when(Site.get(any())).thenReturn(siteMock);
  when(siteMock.getService()).thenReturn(jiraServiceMock);

  when(runMock.getCauses()).thenReturn(null);
  when(taskListenerMock.getLogger()).thenReturn(printStreamMock);
  doNothing().when(printStreamMock).println();

  final ResponseDataBuilder<Object> builder = ResponseData.builder();
  when(jiraServiceMock.getIssueLink(anyString()))
      .thenReturn(builder.successful(true).code(200).message("Success").build());

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
 
Example 3
Source File: TestAgentConsumerWithSleep.java    From chronos with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Before
public void setUp() throws Exception {
  reporting = new NoReporting();
  dao = new H2TestJobDaoImpl();
  dao.setDrivers(drivers);
  dao.init();
  PowerMockito.mockStatic(Utils.class);
  when(Utils.getCurrentTime())
    .thenReturn(new DateTime(0).withZone(DateTimeZone.UTC));
  consumer = new AgentConsumer(dao, reporting, "testing.huffpo.com",
    new MailInfo("", "", "", ""),
    Session.getDefaultInstance(new Properties()), drivers, numOfConcurrentJobs,
    numOfConcurrentReruns, maxReruns, 1, 1);
  consumer.SLEEP_FOR = 1;

  AgentConsumer.setShouldSendErrorReports(false);
}
 
Example 4
Source File: MainTest.java    From nifi-config with Apache License 2.0 6 votes vote down vote up
@Test
public void mainUpdateWithPasswordFromEnvTest() throws Exception {
    PowerMockito.mockStatic(System.class);
    Mockito.when(System.getenv(Main.ENV_NIFI_PASSWORD)).thenReturn("nifi_pass");

    Injector injector = Guice.createInjector(new AbstractModule() {
        protected void configure() {
            bind(AccessService.class).toInstance(accessServiceMock);
            bind(InformationService.class).toInstance(informationServiceMock);
            bind(UpdateProcessorService.class).toInstance(updateProcessorServiceMock);
            // bind(ConnectionPortService.class).toInstance(createRouteServiceMock);
            bind(Integer.class).annotatedWith(Names.named("timeout")).toInstance(10);
            bind(Integer.class).annotatedWith(Names.named("interval")).toInstance(10);
            bind(Boolean.class).annotatedWith(Names.named("forceMode")).toInstance(false);
            bind(Double.class).annotatedWith(Names.named("placeWidth")).toInstance(1200d);
            bind(PositionDTO.class).annotatedWith(Names.named("startPosition")).toInstance(new PositionDTO());
        }
    });
    //given
    PowerMockito.mockStatic(Guice.class);
    Mockito.when(Guice.createInjector((AbstractModule) anyObject())).thenReturn(injector);

    Main.main(new String[]{"-nifi", "http://localhost:8080/nifi-api", "-branch", "\"root>N2\"", "-conf", "adr", "-m", "updateConfig", "-user", "user", "-password", "password"});
    verify(updateProcessorServiceMock).updateByBranch(Arrays.asList("root", "N2"), "adr", false);
    verify(accessServiceMock).addTokenOnConfiguration(false, "user", "nifi_pass");
}
 
Example 5
Source File: TestCreateOrder.java    From huobi_Java with Apache License 2.0 5 votes vote down vote up
@Test
public void testResult_Unexpected() {
  PowerMockito.mockStatic(AccountsInfoMap.class);
  PowerMockito.when(AccountsInfoMap.getUser("12345")).thenReturn(testAccount);
  RestApiRequest<Long> restApiRequest =
      impl.createOrder(CorrectnewOrderRequest);
  JsonWrapper jsonWrapper = JsonWrapper.parseFromString(Errordata);
  thrown.expect(HuobiApiException.class);
  thrown.expectMessage("Get json item field");
  restApiRequest.jsonParser.parseJson(jsonWrapper);
}
 
Example 6
Source File: RNInstabugRepliesModuleTest.java    From Instabug-React-Native with MIT License 5 votes vote down vote up
@Test
public void given$show_whenQuery_thenShouldCallNativeApi() {
    // given
    PowerMockito.mockStatic(Replies.class);
    // when
    rnModule.show();
    // then
    PowerMockito.verifyStatic(VerificationModeFactory.times(1));
    Replies.show();
}
 
Example 7
Source File: RNInstabugReactnativeModuleTest.java    From Instabug-React-Native with MIT License 5 votes vote down vote up
@Test
public void givenArgs$setUserAttribute_whenQuery_thenShouldCallNativeApi() {
    // given
    PowerMockito.mockStatic(Instabug.class);
    String key = "company";
    String value = "Instabug";
    // when
    rnModule.setUserAttribute(key, value);
    // then
    PowerMockito.verifyStatic(VerificationModeFactory.times(1));
    Instabug.setUserAttribute(key, value);
}
 
Example 8
Source File: APIUtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetMediationSequenceUuidCustomSequence() throws Exception {
    APIIdentifier apiIdentifier = Mockito.mock(APIIdentifier.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);

    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);
    Mockito.when(registryService.getGovernanceSystemRegistry(eq(1))).thenReturn(registry);

    Collection collection = Mockito.mock(Collection.class);
    String artifactPath = APIConstants.API_ROOT_LOCATION + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getProviderName() + RegistryConstants.PATH_SEPARATOR +
            apiIdentifier.getApiName() + RegistryConstants.PATH_SEPARATOR + apiIdentifier.getVersion();
    String path = artifactPath + RegistryConstants.PATH_SEPARATOR + "custom" + RegistryConstants.PATH_SEPARATOR;

    Mockito.when(registry.get(eq(path))).thenReturn(collection);

    String[] childPaths = {"test"};
    Mockito.when(collection.getChildren()).thenReturn(childPaths);

    String expectedUUID = UUID.randomUUID().toString();

    InputStream sampleSequence = new FileInputStream(Thread.currentThread().getContextClassLoader().
            getResource("sampleSequence.xml").getFile());

    Resource resource = Mockito.mock(Resource.class);
    Mockito.when(registry.get(eq("test"))).thenReturn(resource);
    Mockito.when(resource.getContentStream()).thenReturn(sampleSequence);
    Mockito.when(resource.getUUID()).thenReturn(expectedUUID);


    String actualUUID = APIUtil.getMediationSequenceUuid("sample", 1, "custom", apiIdentifier);

    Assert.assertEquals(expectedUUID, actualUUID);
    sampleSequence.close();
}
 
Example 9
Source File: TestGetHistoryOrders.java    From huobi_Java with Apache License 2.0 5 votes vote down vote up
@Test
public void testResult_Unexpected() {
  PowerMockito.mockStatic(AccountsInfoMap.class);
  PowerMockito.when(AccountsInfoMap.getAccount("12345", 123L)).thenReturn(testAccount);
  RestApiRequest<List<Order>> restApiRequest =
      impl.getHistoricalOrders(historicalOrdersRequest);
  JsonWrapper jsonWrapper = JsonWrapper.parseFromString(Errordata);
  thrown.expect(HuobiApiException.class);
  thrown.expectMessage("Get json item field");
  restApiRequest.jsonParser.parseJson(jsonWrapper);
}
 
Example 10
Source File: UtilTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = Exception.class)
public void testShouldThrowEceptionWhenSigningFails() throws Exception {
    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(512);
    PrivateKey pvtKey = keygen.generateKeyPair().getPrivate();
    PowerMockito.mockStatic(KeyStoreManager.class);
    KeyStoreManager keyStoreManager = Mockito.mock(KeyStoreManager.class);

    PowerMockito.when(KeyStoreManager.getInstance(Mockito.anyInt())).thenReturn(keyStoreManager);
    Mockito.when(keyStoreManager.getDefaultPrimaryCertificate()).thenReturn(null);
    Mockito.when(keyStoreManager.getDefaultPrivateKey()).thenReturn(pvtKey);

    Util.getAuthHeader("admin");
}
 
Example 11
Source File: APIMRegistryServiceImplTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void getGovernanceRegistryResourceContentTestCase() throws UserStoreException, RegistryException{
    APIMRegistryServiceImpl apimRegistryService = new APIMRegistryServiceImplWrapper();

    System.setProperty(CARBON_HOME, "");
    PrivilegedCarbonContext privilegedCarbonContext = Mockito.mock(PrivilegedCarbonContext.class);
    PowerMockito.mockStatic(PrivilegedCarbonContext.class);
    PowerMockito.when(PrivilegedCarbonContext.getThreadLocalCarbonContext()).thenReturn(privilegedCarbonContext);
    Mockito.when(privilegedCarbonContext.getTenantDomain()).thenReturn(TENANT_DOMAIN);
    Mockito.when(privilegedCarbonContext.getTenantId()).thenReturn(TENANT_ID);

    RealmService realmService = Mockito.mock(RealmService.class);
    TenantManager tenantManager = Mockito.mock(TenantManager.class);
    RegistryService registryService = Mockito.mock(RegistryService.class);
    UserRegistry registry = Mockito.mock(UserRegistry.class);
    Resource resource = Mockito.mock(Resource.class);

    ServiceReferenceHolder serviceReferenceHolder = Mockito.mock(ServiceReferenceHolder.class);
    PowerMockito.mockStatic(ServiceReferenceHolder.class);
    Mockito.when(ServiceReferenceHolder.getInstance()).thenReturn(serviceReferenceHolder);
    Mockito.when(serviceReferenceHolder.getRealmService()).thenReturn(realmService);
    Mockito.when(realmService.getTenantManager()).thenReturn(tenantManager);
    Mockito.when(serviceReferenceHolder.getRegistryService()).thenReturn(registryService);


    Mockito.when(tenantManager.getTenantId(TENANT_DOMAIN)).thenReturn(TENANT_ID);
    Mockito.when(registryService.getGovernanceSystemRegistry(TENANT_ID)).thenReturn(registry);

    Mockito.when(registry.resourceExists("testLocation")).thenReturn(true);
    Mockito.when(registry.get("testLocation")).thenReturn(resource);


    Assert.assertEquals("testContent", apimRegistryService.
            getGovernanceRegistryResourceContent("test.foo", "testLocation"));
}
 
Example 12
Source File: CloudIamAuthNexusProxyVerticleTests.java    From nexus-proxy with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp(final TestContext context) {
    PowerMockito.mockStatic(System.class);
    VARS.entrySet().stream().forEach(e -> PowerMockito.when(System.getenv(e.getKey())).thenReturn(e.getValue()));

    this.vertx = Vertx.vertx();
    this.vertx.deployVerticle(CloudIamAuthNexusProxyVerticle.class.getName(), context.asyncAssertSuccess());
}
 
Example 13
Source File: RemoteXBeeDeviceReadInfo64BitTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.RemoteZigBeeDevice#readDeviceInfo()}.
 * 
 * <p>Verify that device info of a 802.15.4 local device cannot be read if 
 * the class for the specified device is not the right one. It is, there is 
 * an AT command exception reading the parameter.</p>
 * 
 * @throws XBeeException
 * @throws IOException 
 */
@Test
public void testReadDeviceInfoErrorInvalidZigBeeClassFor802Device() throws XBeeException, IOException {
	// Setup the resources for the test.
	XBeeProtocol realProtocol = XBeeProtocol.RAW_802_15_4;
	
	exception.expect(XBeeException.class);
	exception.expectMessage(is(equalTo("Error reading device information: "
			+ "Your module seems to be " + realProtocol 
			+ " and NOT " + remoteZbDevice.getXBeeProtocol() + ". Check if you are using" 
			+ " the appropriate device class.")));
	
	// Return a valid response when requesting the NI parameter value.
	Mockito.doReturn(RESPONSE_NI).when(remoteZbDevice).getParameter(PARAMETER_NI);
	
	// Return a valid response when requesting the HV parameter value.
	Mockito.doReturn(RESPONSE_HV).when(remoteZbDevice).getParameter(PARAMETER_HV);
	
	// Return a valid response when requesting the VR parameter value.
	Mockito.doReturn(RESPONSE_VR).when(remoteZbDevice).getParameter(PARAMETER_VR);
	
	// Return the "real" value of the module protocol.
	PowerMockito.mockStatic(XBeeProtocol.class);
	PowerMockito.when(XBeeProtocol.determineProtocol(Mockito.any(HardwareVersion.class), Mockito.anyString())).thenReturn(realProtocol);
	
	// Execute the method under test.
	remoteZbDevice.readDeviceInfo();
}
 
Example 14
Source File: AuthTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    PowerMockito.mockStatic(AuthJS.class);
    PowerMockito.mockStatic(ScriptRunner.class);
    PowerMockito.when(ScriptRunner.class, "firebaseScript", Mockito.any(Runnable.class)).then(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) {
            ((Runnable) invocation.getArgument(0)).run();
            return null;
        }
    });
    GdxFIRApp.setAutoSubscribePromises(false);
}
 
Example 15
Source File: ConnectToAccessPointTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.WiFiDevice#disconnect()}.
 * 
 * <p>Verify that the Wi-Fi module cannot disconnect from the access point 
 * if the AI status is empty.</p>
 * 
 * @throws Exception 
 */
@Test
public final void testDisconnectEmptyAIStatus() throws Exception {
	// Setup the resources for the test.
	PowerMockito.doNothing().when(wifiDevice).executeParameter("NR");
	PowerMockito.doReturn(new byte[0]).when(wifiDevice).getParameter("AI");
	
	// Get the current time.
	currentMillis = System.currentTimeMillis();
	
	// Configure the number of ticks (times) the sleep method should be called.
	int ticks = wifiDevice.getAccessPointTimeout()/100;
	
	// Prepare the System class to return our fixed currentMillis variable when requested.
	PowerMockito.mockStatic(System.class);
	PowerMockito.when(System.currentTimeMillis()).thenReturn(currentMillis);
	
	// When the sleep method is called, add 100ms to the currentMillis variable.
	PowerMockito.doAnswer(new Answer<Object>() {
		public Object answer(InvocationOnMock invocation) throws Exception {
			Object[] args = invocation.getArguments();
			int sleepTime = (Integer)args[0];
			changeMillisToReturn(sleepTime);
			return null;
		}
	}).when(wifiDevice, METHOD_SLEEP, Mockito.anyInt());
	
	// Call the method under test.
	boolean disconnected = wifiDevice.disconnect();
	
	// Verify the result.
	assertThat("Module should not have disconnected", disconnected, is(equalTo(false)));
	// Verify that the sleep method was called 'ticks' times.
	PowerMockito.verifyPrivate(wifiDevice, Mockito.times(ticks)).invoke(METHOD_SLEEP, 100);
}
 
Example 16
Source File: XBeeDeviceReadInfoTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.XBeeDevice#readDeviceInfo()}.
 * 
 * <p>Verify that device info of a Cellular local device cannot be read if 
 * the class for the specified device is not the right one. It is, there is 
 * an AT command exception reading the parameter.</p>
 * 
 * @throws XBeeException
 * @throws IOException 
 */
@Test
public void testReadDeviceInfoErrorInvalidWiFiClassForCellularDevice() throws XBeeException, IOException {
	// Setup the resources for the test.
	XBeeProtocol realProtocol = XBeeProtocol.CELLULAR;
	
	exception.expect(XBeeException.class);
	exception.expectMessage(is(equalTo("Error reading device information: "
			+ "Your module seems to be " + realProtocol 
			+ " and NOT " + wifiDevice.getXBeeProtocol() + ". Check if you are using" 
			+ " the appropriate device class.")));
	
	// Return a valid response when requesting the SH parameter value.
	Mockito.doReturn(RESPONSE_SH).when(wifiDevice).getParameter(PARAMETER_SH);
	
	// Return a valid response when requesting the SL parameter value.
	Mockito.doReturn(RESPONSE_SL).when(wifiDevice).getParameter(PARAMETER_SL);
	
	// Return a valid response when requesting the NI parameter value.
	Mockito.doReturn(RESPONSE_NI).when(wifiDevice).getParameter(PARAMETER_NI);
	
	// Return a valid response when requesting the HV parameter value.
	Mockito.doReturn(RESPONSE_HV).when(wifiDevice).getParameter(PARAMETER_HV);
	
	// Return a valid response when requesting the VR parameter value.
	Mockito.doReturn(RESPONSE_VR).when(wifiDevice).getParameter(PARAMETER_VR);
	
	// Return the "real" value of the module protocol.
	PowerMockito.mockStatic(XBeeProtocol.class);
	PowerMockito.when(XBeeProtocol.determineProtocol(Mockito.any(HardwareVersion.class), Mockito.anyString())).thenReturn(realProtocol);
	
	// Execute the method under test.
	wifiDevice.readDeviceInfo();
}
 
Example 17
Source File: AAPSMocker.java    From AndroidAPS with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void mockProfileFunctions() {
    PowerMockito.mockStatic(ProfileFunctions.class);
    profileFunctions = PowerMockito.mock(ProfileFunctions.class);
    PowerMockito.when(ProfileFunctions.getSystemUnits()).thenReturn(Constants.MGDL);
    PowerMockito.when(ProfileFunctions.getInstance()).thenReturn(profileFunctions);
    profile = getValidProfile();
    PowerMockito.when(ProfileFunctions.getInstance().getProfile()).thenReturn(profile);
    PowerMockito.when(ProfileFunctions.getInstance().getProfileName()).thenReturn(TESTPROFILENAME);
}
 
Example 18
Source File: ConsistencyTest.java    From CodeDefenders with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Context getInitialContext(Hashtable<?, ?> environment) throws NamingException {
    System.out.println("ParallelizeAntRunnerTest.MyContextFactory.getInitialContext()");
    InitialContext mockedInitialContext = PowerMockito.mock(InitialContext.class);
    NamingEnumeration<NameClassPair> mockedEnumeration = PowerMockito.mock(NamingEnumeration.class);
    // Look at this again ...
    PowerMockito.mockStatic(NamingEnumeration.class);
    //
    PowerMockito.when(mockedEnumeration.hasMore()).thenReturn(true, true, true, true, false);
    PowerMockito.when(mockedEnumeration.next()).thenReturn(
            new NameClassPair("data.dir", String.class.getName()),
            new NameClassPair("parallelize", String.class.getName()),
            new NameClassPair("mutant.coverage", String.class.getName()),
            new NameClassPair("ant.home", String.class.getName())//
    );
    //
    PowerMockito.when(mockedInitialContext.toString()).thenReturn("Mocked Initial Context");
    PowerMockito.when(mockedInitialContext.list("java:/comp/env")).thenReturn(mockedEnumeration);
    //
    Context mockedEnvironmentContext = PowerMockito.mock(Context.class);
    PowerMockito.when(mockedInitialContext.lookup("java:/comp/env")).thenReturn(mockedEnvironmentContext);

    PowerMockito.when(mockedEnvironmentContext.lookup("mutant.coverage")).thenReturn("enabled");
    // FIXMED
    PowerMockito.when(mockedEnvironmentContext.lookup("parallelize")).thenReturn("enabled");
    //
    PowerMockito.when(mockedEnvironmentContext.lookup("data.dir"))
            .thenReturn(codedefendersHome.getAbsolutePath());

    PowerMockito.when(mockedEnvironmentContext.lookup("ant.home")).thenReturn("/usr/local");
    //
    return mockedInitialContext;
}
 
Example 19
Source File: DitoTrackerTest.java    From DarylAndroidTracker with MIT License 4 votes vote down vote up
@Before
public void setUp() {
    PowerMockito.mockStatic(DitoSDK.class);
    this.subject = new DitoTracker(userProperties);
}
 
Example 20
Source File: MemoryTaskEntityTest.java    From analyzer-of-android-for-Apache-Weex with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    PowerMockito.mockStatic(MemorySampler.class);
    Mockito.when(MemorySampler.getMemoryUsage()).thenReturn(1.5);
    entity = new MemoryTaskEntity();
}