org.powermock.api.mockito.PowerMockito Java Examples

The following examples show how to use org.powermock.api.mockito.PowerMockito. 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: TestJvmUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void findMainClass_jar_normal() throws Exception {

  URL url = PowerMockito.mock(URL.class);

  String command = "a.jar";
  String manifestUri = "jar:file:" + new File(command).getAbsolutePath() + "!/" + JarFile.MANIFEST_NAME;
  PowerMockito.whenNew(URL.class).withParameterTypes(String.class)
      .withArguments(manifestUri).thenReturn(url);

  String content = String.format("Manifest-Version: 1.0\nMain-Class: %s\n", TestJvmUtils.class.getName());
  InputStream inputStream = new ByteArrayInputStream(content.getBytes());
  PowerMockito.when(url.openStream()).thenReturn(inputStream);

  System.setProperty(JvmUtils.SUN_JAVA_COMMAND, command + " arg");

  Assert.assertEquals(TestJvmUtils.class, JvmUtils.findMainClass());
}
 
Example #2
Source File: ConnectToAccessPointTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.WiFiDevice#connect(String, String)}.
 * 
 * <p>Verify that the Wi-Fi module can connect to to an access point successfully 
 * providing just the SSID of the access point.</p>
 * 
 * @throws XBeeException 
 */
@Test
public final void testConnectSuccessSSID() throws XBeeException {
	// Setup the resources for the test.
	String ssid = "AP SSID";
	String password = "password";
	
	// Return the mocked access point when asked for one.
	PowerMockito.doReturn(mockedAccessPoint).when(wifiDevice).getAccessPoint(ssid);
	
	// Return true when asked to connect to an access point.
	PowerMockito.doReturn(true).when(wifiDevice).connect(Mockito.eq(mockedAccessPoint), Mockito.anyString());
	
	
	// Call the method under test.
	boolean connected = wifiDevice.connect(ssid, password);
	
	// Verify the result.
	assertThat("Module should have connected", connected, is(equalTo(true)));
	// Verify that the connect method was called one time.
	Mockito.verify(wifiDevice, Mockito.times(1)).connect(Mockito.eq(mockedAccessPoint), Mockito.eq(password));
}
 
Example #3
Source File: FunctionApiV2ResourceTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = RestException.class, expectedExceptionsMessageRegExp = "upload failure")
public void testRegisterFunctionUploadFailure() throws Exception {
    try {
        mockStatic(WorkerUtils.class);
        doThrow(new IOException("upload failure")).when(WorkerUtils.class);

        WorkerUtils.uploadFileToBookkeeper(
                anyString(),
                any(File.class),
                any(Namespace.class));
        PowerMockito.when(WorkerUtils.class, "dumpToTmpFile", any()).thenCallRealMethod();

        when(mockedManager.containsFunction(eq(tenant), eq(namespace), eq(function))).thenReturn(false);

        registerDefaultFunction();
    } catch (RestException re) {
        assertEquals(re.getResponse().getStatusInfo(), Response.Status.INTERNAL_SERVER_ERROR);
        throw re;
    }
}
 
Example #4
Source File: EsRetryOnParticularErrorTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * EsType_putMappingメソッドで初回にIndexMissingExceptionが投げられた場合のテスト.
 */
@Test
public void EsType_putMappingメソッドで初回にIndexMissingExceptionが投げられた場合のテスト() {
    PowerMockito.mockStatic(EsClientException.class);
    EsTypeImpl esTypeObject = Mockito.spy(new EsTypeImpl("dummy", "Test", "TestRoutingId", 0, 0, null));

    // EsType#asyncPutMapping()が呼ばれた場合に、IndexMissingExceptionを投げる。
    // 送出する例外オブジェクトのモックを作成
    IndexNotFoundException toBeThrown = new IndexNotFoundException("abc");
    Mockito.doThrow(toBeThrown)
            .when(esTypeObject)
            .asyncPutMapping(Mockito.anyMapOf(String.class, Object.class));
    // メソッド呼び出し
    try {
        esTypeObject.putMapping(null);
        fail("EsClientException should be thrown.");
    } catch (EsClientException.EsIndexMissingException e) {
        assertTrue(e.getCause() instanceof IndexNotFoundException);
    }
}
 
Example #5
Source File: EditVersionStepTest.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<Void> builder = ResponseData.builder();
  when(jiraServiceMock.updateVersion(anyString(), any()))
      .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 #6
Source File: ProfileManagerImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This test case tests handling SQLException when updating profile",
      dependsOnMethods = {"testUpdateProfileThrowingFeatureManagerDAOException"},
      expectedExceptions = IllegalTransactionStateException.class)
public void testUpdateProfileThrowingIllegalTransactionStateException() throws Exception {
    //Retrieving profile object
    Profile savedProfile = profileManager.getProfile(profile1.getProfileId());

    Pair<Connection, Pair<DataSource, DataSource>> pair = mockConnection();
    PowerMockito.doThrow(new SQLException()).when(pair.first()).setAutoCommit(anyBoolean());

    String newProfileName = "Updated Test Profile";
    savedProfile.setProfileName(newProfileName);
    try {
        profileManager.updateProfile(savedProfile);
    } finally {
        PolicyManagementDAOFactory.init(pair.second().first());
    }
}
 
Example #7
Source File: DbOperationControllerTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testreadAll() {
  PowerMockito.mockStatic(RequestInterceptor.class);
  when(RequestInterceptor.verifyRequestData(Mockito.anyObject()))
      .thenReturn("{userId} uuiuhcf784508 8y8c79-fhh");
  Map<String, Object> requestMap = new HashMap<>();
  Map<String, Object> innerMap = new HashMap<>();
  innerMap.put(ENTITY_NAME, entityName);
  innerMap.put(INDEXED, true);

  /*Map<String , Object> payLoad = new HashMap<>();
  payLoad.put(JsonKey.USER_ID , "usergt78y4ry8");
  payLoad.put(JsonKey.ID , "ggudy8d8ydyy8ddy9");
  innerMap.put(PAYLOAD , payLoad);*/
  requestMap.put(JsonKey.REQUEST, innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req =
      new RequestBuilder().bodyJson(json).uri("/v1/object/read/list").method("POST");
  //req.headers(headerMap);
  Result result = Helpers.route(application,req);
  assertEquals(200, result.status());
}
 
Example #8
Source File: APIMWSDLReaderTest.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testSetServiceDefinitionWithInvalidAPIGatewayEndpoints() throws Exception {
    PowerMockito.mockStatic(APIUtil.class);
    API api = getAPIForTesting();
    String environmentName = "Production and Sandbox";
    String environmentType = "hybrid";

    APIMWSDLReader wsdlReader = new APIMWSDLReader("");
    byte[] content = IOUtils.toByteArray(
            Thread.currentThread().getContextClassLoader().getResourceAsStream("wsdls/invalidEndpointURL.wsdl"));
    Definition definition = wsdlReader.getWSDLDefinitionFromByteContent(content, false);
    try {
        wsdlReader.setServiceDefinition(definition, api, environmentName, environmentType);
        wsdlReader.getWSDL(definition);
        Assert.assertNotNull(definition.getServices());
    } catch (APIManagementException e) {
        Assert.fail("Unexpected exception occurred while updating service endpoint address");
    }
}
 
Example #9
Source File: IDataReceiveListenerXBeeTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.listeners.IDataReceiveListener#dataReceived(XBeeMessage)} and
 * {@link com.digi.xbee.api.DataReader#packetReceived(XBeePacket)}.
 * 
 * <p>Verify that, when subscribed to receive data and a Receive packet is received, the 
 * callback of the listener is executed.</p>
 * 
 * @throws Exception
 */
@Test
public void testDataReceiveSubscribedReceive() throws Exception {
	// Whenever a new remote XBee device needs to be instantiated, return the mocked one.
	PowerMockito.whenNew(RemoteXBeeDevice.class).withAnyArguments().thenReturn(remoteXBeeDevice);
	
	// Subscribe to listen for data.
	dataReader.addDataReceiveListener(receiveDataListener);
	
	// Fire the private packetReceived method of the dataReader with a ReceivePacket.
	Whitebox.invokeMethod(dataReader, PACKET_RECEIVED_METHOD, receivePacket);
	
	// Verify that the notifyDataReceived private method was called.
	PowerMockito.verifyPrivate(dataReader, Mockito.times(1)).invoke(NOTIFY_DATA_RECEIVED_METHOD, 
			Mockito.any(XBeeMessage.class));
	
	// Verify that the dataReceived method of the listener was executed one time.
	Mockito.verify(receiveDataListener, Mockito.times(1)).dataReceived(Mockito.any(XBeeMessage.class));
	
	// All the parameters of our listener should be correct.
	assertEquals(XBEE_64BIT_ADDRESS, receiveDataListener.get64BitAddress());
	assertArrayEquals(RECEIVED_DATA_BYTES, receiveDataListener.getData());
	assertFalse(receiveDataListener.isBroadcast());
}
 
Example #10
Source File: EsRetryOnParticularErrorTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * EsType_deleteメソッドで初回にIndexMissingExceptionを根本原因に持つ例外が投げられた場合のテスト.
 */
@Test
public void EsType_deleteメソッドで初回にIndexMissingExceptionを根本原因に持つ例外が投げられた場合のテスト() {
    PowerMockito.mockStatic(EsClientException.class);
    EsTypeImpl esTypeObject = Mockito.spy(new EsTypeImpl("dummy", "Test", "TestRoutingId", 0, 0, null));

    // EsType#asyncDelete()が呼ばれた場合に、IndexMissingExceptionを根本原因に持つ例外を投げる。
    // 送出する例外オブジェクトを作成
    SettingsException toBeThrown = new SettingsException("foo", new IndexMissingException(new Index("dummy")));
    Mockito.doThrow(toBeThrown)
            .when(esTypeObject)
            .asyncDelete(Mockito.anyString(), Mockito.anyLong());
    // メソッド呼び出し
    try {
        esTypeObject.delete("dummyId", 1);
        fail("EsClientException should be thrown.");
    } catch (EsClientException.EsIndexMissingException e) {
        assertTrue(e.getCause() instanceof SettingsException);
        assertTrue(e.getCause().getCause() instanceof IndexMissingException);
    }
}
 
Example #11
Source File: NotificationManagementServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the behaviour of getNotifications method under different conditions")
public void testGetNotifications() throws NotificationManagementException {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotificationManagementService"))
            .toReturn(this.notificationManagementService);
    Response response = notificationManagement.getNotifications("NEW", "test", 0, 10);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed");
    response = notificationManagement.getNotifications(null, "test", 0, 10);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(), "Notification retrieval failed");
    Mockito.reset(this.notificationManagementService);
    Mockito.doThrow(new NotificationManagementException()).when(notificationManagementService)
            .getAllNotifications(Mockito.any());
    response = notificationManagement.getNotifications(null, "test", 0, 10);
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            "Notification retrieval succeeded with issues in NotificationManagement OSGI service");
    Mockito.reset(this.notificationManagementService);
}
 
Example #12
Source File: UserDataSchemaCacheTest.java    From io with Apache License 2.0 6 votes vote down vote up
/**
 * isChangedメソッドで登録済みのキャッシュが存在しない場合trueを返すこと.
 * @throws Exception 実行エラー
 */
@Test
public void isChangedメソッドで登録済みのキャッシュが存在しない場合trueを返すこと() throws Exception {
    String nodeId = "node_VVVVVVVVV1";
    Map<String, Object> schemaToCache = new HashMap<String, Object>();
    schemaToCache.put("SchemaCacheTestKey001", "testValue");
    Long now = new Date().getTime();
    schemaToCache.put("disabledTime", now);

    // テスト用のキャッシュクラスに接続するよう設定を変更
    MockMemcachedClient mockMemcachedClient = new MockMemcachedClient();
    PowerMockito.spy(UserDataSchemaCache.class);
    PowerMockito.when(UserDataSchemaCache.class, "getMcdClient").thenReturn(mockMemcachedClient);

    // キャッシュの設定を有効にする
    PowerMockito.spy(DcCoreConfig.class);
    PowerMockito.when(DcCoreConfig.class, "isSchemaCacheEnabled").thenReturn(true);

    // isChanged?
    Map<String, Object> schemaToCacheNew = new HashMap<String, Object>();
    schemaToCacheNew.put("SchemaCacheTestKey002", "testValue");
    schemaToCacheNew.put("disabledTime", now + 1);
    assertThat(UserDataSchemaCache.isChanged(nodeId, schemaToCacheNew)).isTrue();
}
 
Example #13
Source File: SofaRpcProviderInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    sofaRpcProviderInterceptor = new SofaRpcProviderInterceptor();

    PowerMockito.mockStatic(RpcInternalContext.class);

    when(sofaRequest.getMethodName()).thenReturn("test");
    when(sofaRequest.getMethodArgSigs()).thenReturn(new String[] {"String"});
    when(sofaRequest.getMethodArgs()).thenReturn(new Object[] {"abc"});
    when(sofaRequest.getInterfaceName()).thenReturn("org.apache.skywalking.apm.test.TestSofaRpcService");
    PowerMockito.when(RpcInternalContext.getContext()).thenReturn(rpcContext);
    when(rpcContext.isConsumerSide()).thenReturn(false);
    final ProviderInfo providerInfo = new ProviderInfo();
    providerInfo.setHost("127.0.0.1");
    providerInfo.setPort(12200);
    when(rpcContext.getProviderInfo()).thenReturn(providerInfo);
    allArguments = new Object[] {sofaRequest};
    argumentTypes = new Class[] {sofaRequest.getClass()};
    Config.Agent.SERVICE_NAME = "SOFARPC-TestCases-APP";
}
 
Example #14
Source File: MapRepositoryCustomImplTest.java    From osiris with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@Test(expected=QueryException.class)
public void findByIDAppAndQueryErrorQueryTesTest() throws Exception{

	String idApplication = "1";  
	String queryJSON = "{ geometry:{ $geoWithin: $centerSphere:[ [20.05,20.01] , 0.05]} } }";	
	Integer pageIndex=5;
	Integer pageSize= 20;		
				
	//Fixture		 	    	    	    	    
	PowerMockito.whenNew(BasicQuery.class).withArguments(queryJSON).thenThrow(Exception.class);						
					 		
	//Experimentation
	mapRepositoryCustomImpl.searchIDAppAndQuery(idApplication, queryJSON, pageIndex, pageSize);
	
	//Expectations

}
 
Example #15
Source File: UTest.java    From Taskbar with Apache License 2.0 6 votes vote down vote up
private void testHasBrokenSetLaunchBoundsApiWithValidApiVersion() throws Exception {
    PowerMockito.spy(U.class);
    BooleanAnswer isSamsungDeviceAnswer = new BooleanAnswer();
    BooleanAnswer isNvidiaDevice = new BooleanAnswer();
    when(U.isSamsungDevice()).thenAnswer(isSamsungDeviceAnswer);
    when(U.class, "isNvidiaDevice").thenAnswer(isNvidiaDevice);
    isSamsungDeviceAnswer.answer = false;
    isNvidiaDevice.answer = false;
    assertTrue(U.hasBrokenSetLaunchBoundsApi());
    isSamsungDeviceAnswer.answer = false;
    isNvidiaDevice.answer = true;
    assertFalse(U.hasBrokenSetLaunchBoundsApi());
    isSamsungDeviceAnswer.answer = true;
    isNvidiaDevice.answer = false;
    assertFalse(U.hasBrokenSetLaunchBoundsApi());
    isSamsungDeviceAnswer.answer = true;
    isNvidiaDevice.answer = true;
    assertFalse(U.hasBrokenSetLaunchBoundsApi());
}
 
Example #16
Source File: ValidatorTest.java    From AwesomeValidation with MIT License 6 votes vote down vote up
public void testSetTextInputLayoutWithActivityAndPattern() {
    Activity mockActivity = mock(Activity.class, RETURNS_DEEP_STUBS);
    int viewId = 1;
    Pattern mockPattern = PowerMockito.mock(Pattern.class);
    int errMsgId = 9;
    String errMsg = "Error";
    TextInputLayout mockTextInputLayout = mock(TextInputLayout.class);
    when(mockActivity.findViewById(eq(viewId))).thenReturn(mockTextInputLayout);
    when(mockActivity.getResources().getString(eq(errMsgId))).thenReturn(errMsg);
    mSpiedValidator.set(mockActivity, viewId, mockPattern, errMsgId);
    assertEquals(1, mSpiedValidator.mValidationHolderList.size());
    ValidationHolder validationHolder = mSpiedValidator.mValidationHolderList.get(0);
    assertEquals(mockTextInputLayout, validationHolder.getTextInputLayout());
    assertEquals(mockPattern, validationHolder.getPattern());
    assertEquals(errMsg, validationHolder.getErrMsg());
}
 
Example #17
Source File: APIKeyValidatorTestCase.java    From carbon-apimgt with Apache License 2.0 6 votes vote down vote up
@Test
public void testDatasourceConfigurationAndCleanup() throws Exception {

    AxisConfiguration axisConfig = Mockito.mock(AxisConfiguration.class);
    WSAPIKeyDataStore wsDataStore = Mockito.mock(WSAPIKeyDataStore.class);
    PowerMockito.whenNew(WSAPIKeyDataStore.class).withNoArguments().thenReturn(wsDataStore);

    APIKeyValidator wsKeyValidator = new APIKeyValidator(axisConfig) {
        @Override
        protected String getKeyValidatorClientType() {

            return "WSClient";
        }
    };

    // test cleanup for WSClient
    wsKeyValidator.cleanup();
    Mockito.verify(wsDataStore, Mockito.times(1)).cleanup();
}
 
Example #18
Source File: ProcessImageInputValidatorTest.java    From cs-actions with Apache License 2.0 6 votes vote down vote up
@Test
public void validate_destinationFolderIsNotDirectory_ValidationException() {
    //Arrange
    ProcessImageInput abbyyRequestMock = mockAbbyyRequest();

    Path destinationFolderMock = mock(Path.class);
    PowerMockito.when(Files.exists(destinationFolderMock)).thenReturn(true);
    PowerMockito.when(Files.isDirectory(destinationFolderMock)).thenReturn(false);
    when(abbyyRequestMock.getDestinationFile()).thenReturn(destinationFolderMock);

    //Act
    ValidationException ex = this.sut.validate(abbyyRequestMock);

    //Assert
    assertNotNull(ex);
}
 
Example #19
Source File: NotificationListenerTests.java    From appium-uiautomator2-server with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() {
    toastText =  new ArrayList<>();
    toastText.add("toast text");

    originalAccessibilityEventListener = mock(OnAccessibilityEventListener.class);
    PowerMockito.mockStatic(InstrumentationRegistry.class);
    when(InstrumentationRegistry.getInstrumentation()).thenReturn(null);

    PowerMockito.mockStatic(UiDevice.class);
    when(UiDevice.getInstance(null)).thenReturn(mock(UiDevice.class));
    when(UiDevice.getInstance()).thenReturn(mock(UiDevice.class));

    PowerMockito.mockStatic(UiAutomatorBridge.class);
    when(UiAutomatorBridge.getInstance()).thenReturn(mock(UiAutomatorBridge.class));

    PowerMockito.mockStatic(UiAutomation.class);
    uiAutomation = mock(UiAutomation.class);
    when(UiAutomation.getInstance()).thenReturn(uiAutomation);
    when(uiAutomation.getOnAccessibilityEventListener())
            .thenReturn(originalAccessibilityEventListener);

    notificationListener = spy(new NotificationListener());
}
 
Example #20
Source File: DeleteIssueLinkStepTest.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.deleteIssueLink(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 #21
Source File: CachesTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void testPullRequestCacheLoaderWithoutObjectMetadataAction() throws Exception {

    ContributorMetadataAction contributorMetadataAction = new ContributorMetadataAction("Hates Cake", "He hates cake", "[email protected]");
    when(job.getAction(ContributorMetadataAction.class)).thenReturn(contributorMetadataAction);

    PowerMockito.mockStatic(ExtensionList.class);

    ExtensionList<SCMHead.HeadByItem> extensionList = mock(ExtensionList.class);
    when(extensionList.iterator()).thenReturn(Lists.<SCMHead.HeadByItem>newArrayList(new HeadByItemForTest()).iterator());
    when(ExtensionList.lookup(SCMHead.HeadByItem.class)).thenReturn(extensionList);

    Caches.PullRequestCacheLoader loader = new Caches.PullRequestCacheLoader(jenkins);
    BranchImpl.PullRequest pr = loader.load(job.getFullName()).orNull();

    assertNotNull(pr);
    assertEquals("Hates Cake", pr.getAuthor());
    assertEquals("1", pr.getId());
    assertNull(pr.getTitle());
    assertNull(pr.getUrl());
}
 
Example #22
Source File: InMemCuboidMapperTest.java    From kylin with Apache License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
    createTestMetadata();
    FileUtils.deleteDirectory(new File("./meta"));
    FileUtils.copyDirectory(new File(getTestConfig().getMetadataUrl().toString()), new File("./meta"));

    cubeName = "test_kylin_cube_with_slr_1_new_segment";
    cube = CubeManager.getInstance(KylinConfig.getInstanceFromEnv()).getCube(cubeName);
    inMemCuboidMapper = new InMemCuboidMapper<>();
    mapDriver = MapDriver.newMapDriver(inMemCuboidMapper);

    PowerMockito.stub(PowerMockito.method(CuboidSchedulerUtil.class, "getCuboidSchedulerByMode", CubeSegment.class,
            String.class)).toReturn(cube.getCuboidScheduler());
    IMRBatchCubingInputSide mockInputSide = createMockInputSide();
    PowerMockito.stub(PowerMockito.method(MRUtil.class, "getBatchCubingInputSide")).toReturn(mockInputSide);

}
 
Example #23
Source File: DeviceAgentServiceTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "Test publish events when device access authorization exception is thrown.")
public void testPublishEventsWithDeviceAccessAuthorizationException() throws DeviceAccessAuthorizationException {
    PowerMockito.stub(PowerMockito.method(PrivilegedCarbonContext.class, "getThreadLocalCarbonContext"))
            .toReturn(this.privilegedCarbonContext);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class,
            "getDeviceAccessAuthorizationService")).toReturn(this.deviceAccessAuthorizationService);
    Mockito.when(this.deviceAccessAuthorizationService.isUserAuthorized(Mockito.any(DeviceIdentifier.class)))
            .thenThrow(new DeviceAccessAuthorizationException());
    Mockito.when(this.privilegedCarbonContext.getTenantDomain())
            .thenReturn(MultitenantConstants.SUPER_TENANT_DOMAIN_NAME);
    Map<String, Object> payload = new HashMap<>();
    Response response = this.deviceAgentService.publishEvents(payload, TEST_DEVICE_TYPE, TEST_DEVICE_IDENTIFIER);
    Assert.assertNotNull(response, "Response should not be null");
    Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            "The response status should be 500");
    List<Object> payloadList = new ArrayList<>();
    Response response2 = this.deviceAgentService.publishEvents(payloadList, TEST_DEVICE_TYPE,
            TEST_DEVICE_IDENTIFIER);
    Assert.assertNotNull(response2, "Response should not be null");
    Assert.assertEquals(response2.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(),
            "The response status should be 500");
    Mockito.reset(this.deviceAccessAuthorizationService);
}
 
Example #24
Source File: BadgrServiceImplBadgeAssertionTest.java    From sunbird-lms-service with MIT License 6 votes vote down vote up
@Test
public void testRevokeAssertionFailure() throws IOException {
  PowerMockito.when(
          HttpUtil.sendDeleteRequest(Mockito.anyString(), Mockito.anyMap(), Mockito.anyString()))
      .thenReturn(new HttpUtilResponse(BADGE_ASSERTION_REVOKE_RESPONSE_FAILURE, 400));
  PowerMockito.when(badgrServiceImpl.getEmail(Mockito.any(), Mockito.any()))
      .thenReturn(VALUE_RECIPIENT_EMAIL);

  request.put(BadgingJsonKey.ASSERTION_ID, VALUE_ASSERTION_ID);
  request.put(BadgingJsonKey.RECIPIENT_ID, VALUE_RECIPIENT_ID);
  request.put(BadgingJsonKey.RECIPIENT_TYPE, VALUE_RECIPIENT_TYPE_USER);
  request.put(BadgingJsonKey.REVOCATION_REASON, VALUE_REVOCATION_REASON);

  boolean thrown = false;

  try {
    badgrServiceImpl.revokeAssertion(request);
  } catch (ProjectCommonException exception) {
    thrown = true;
    assertEquals(ResponseCode.CLIENT_ERROR.getResponseCode(), exception.getResponseCode());
  }

  assertEquals(true, thrown);
}
 
Example #25
Source File: ConfigurationServiceImplTest.java    From carbon-device-mgt with Apache License 2.0 6 votes vote down vote up
@Test(description = "This method tests the updateConfiguration method under valid conditions.", dependsOnMethods
        = {"testGetConfigurationWithSuccessConditions"})
public void testUpdateConfigurationUnderValidConditions() throws ConfigurationManagementException {
    Mockito.reset(platformConfigurationManagementService);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getPlatformConfigurationManagementService"))
            .toReturn(platformConfigurationManagementService);
    PowerMockito
            .stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getNotifierFrequency", PlatformConfiguration.class))
            .toReturn(60);
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "scheduleTaskService", int.class))
            .toReturn(null);
    Mockito.doReturn(platformConfiguration).when(platformConfigurationManagementService)
            .getConfiguration(Mockito.any());
    Mockito.doReturn(true).when(platformConfigurationManagementService)
            .saveConfiguration(Mockito.any(), Mockito.any());
    Response response = configurationManagementService.updateConfiguration(platformConfiguration);
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
            "updateConfiguration request failed with valid parameters");
}
 
Example #26
Source File: AuthTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Test
public void signOut_fail() {
    // Given
    Auth auth = new Auth();
    BiConsumer biConsumer = Mockito.mock(BiConsumer.class);
    Mockito.doThrow(new RuntimeException()).when(firebaseAuth).signOut();

    // When
    auth.signOut().fail(biConsumer);

    // Then
    PowerMockito.verifyStatic(FirebaseAuth.class, VerificationModeFactory.times(1));
    FirebaseAuth.getInstance();
    Mockito.verify(firebaseAuth, VerificationModeFactory.times(1)).signOut();
    Mockito.verify(biConsumer, VerificationModeFactory.times(1)).accept(Mockito.nullable(String.class), Mockito.any(Exception.class));
}
 
Example #27
Source File: WriterFactoryTest.java    From skywalking with Apache License 2.0 5 votes vote down vote up
@Test
public void returnFileWriterWriteWithBlankLoggingDir() {
    Config.Logging.OUTPUT = LogOutput.FILE;
    PowerMockito.mockStatic(SnifferConfigInitializer.class);
    PowerMockito.mockStatic(AgentPackagePath.class);
    BDDMockito.given(SnifferConfigInitializer.isInitCompleted()).willReturn(true);
    BDDMockito.given(AgentPackagePath.isPathFound()).willReturn(true);

    assertTrue(SnifferConfigInitializer.isInitCompleted());
    assertTrue(AgentPackagePath.isPathFound());

    IWriter logWriter = WriterFactory.getLogWriter();
    PowerMockito.verifyStatic();
    assertTrue(logWriter instanceof FileWriter);
}
 
Example #28
Source File: OrgExternalServiceTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Before
public void setUp() {
  orgExternalService = new OrgExternalService();
  cassandraOperation = PowerMockito.mock(CassandraOperation.class);
  PowerMockito.mockStatic(ServiceFactory.class);
  when(ServiceFactory.getInstance()).thenReturn(cassandraOperation);
}
 
Example #29
Source File: ReactNativeNotificationsHandlerTest.java    From react-native-azurenotificationhub with MIT License 5 votes vote down vote up
@Test
public void testSendBroadcastIntent() throws Exception {
    final int delay = 1000;

    Intent intent = PowerMockito.mock(Intent.class);

    sendBroadcast(mReactApplicationContext, intent, delay);
    mWorkerTask.getValue().run();

    PowerMockito.verifyStatic(ReactNativeUtil.class);
    ReactNativeUtil.runInWorkerThread(any(Runnable.class));
    verify(mLocalBroadcastManager, times(1)).sendBroadcast(intent);
}
 
Example #30
Source File: DeviceTypeManagementAdminServiceTest.java    From carbon-device-mgt with Apache License 2.0 5 votes vote down vote up
@Test(description = "Test get all the device types.")
public void testGetDeviceTypes() {
    PowerMockito.stub(PowerMockito.method(DeviceMgtAPIUtils.class, "getDeviceManagementService"))
            .toReturn(this.deviceManagementProviderService);
    Response response = this.deviceTypeManagementAdminService.getDeviceTypes();
    Assert.assertNotNull(response, "The response should not be null");
    Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode(),
            "The Response status code should be 200.");
}