java.util.EmptyStackException#org.powermock.api.mockito.PowerMockito源码实例Demo

下面列出了java.util.EmptyStackException#org.powermock.api.mockito.PowerMockito 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: io   文件: EsRetryOnParticularErrorTest.java
/**
 * 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);
    }
}
 
@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());
    }
}
 
源代码3 项目: carbon-apimgt   文件: APIMWSDLReaderTest.java
@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");
    }
}
 
@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());
}
 
源代码5 项目: jira-steps-plugin   文件: EditVersionStepTest.java
@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);

}
 
源代码6 项目: xbee-java   文件: ConnectToAccessPointTest.java
/**
 * 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));
}
 
源代码7 项目: pulsar   文件: FunctionApiV2ResourceTest.java
@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;
    }
}
 
源代码8 项目: xbee-java   文件: IDataReceiveListenerXBeeTest.java
/**
 * 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());
}
 
@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);
}
 
@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";
}
 
源代码11 项目: gdx-fireapp   文件: AuthTest.java
@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));
}
 
@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");
}
 
@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);
}
 
源代码14 项目: blueocean-plugin   文件: CachesTest.java
@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());
}
 
@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);
}
 
@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());
}
 
源代码17 项目: carbon-apimgt   文件: APIKeyValidatorTestCase.java
@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();
}
 
源代码18 项目: servicecomb-java-chassis   文件: TestJvmUtils.java
@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());
}
 
源代码19 项目: AwesomeValidation   文件: ValidatorTest.java
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());
}
 
@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);
}
 
源代码21 项目: kylin   文件: InMemCuboidMapperTest.java
@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);

}
 
源代码22 项目: carbon-device-mgt   文件: DeviceAgentServiceTest.java
@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);
}
 
源代码23 项目: osiris   文件: MapRepositoryCustomImplTest.java
@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

}
 
源代码24 项目: Taskbar   文件: UTest.java
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());
}
 
源代码25 项目: io   文件: UserDataSchemaCacheTest.java
/**
 * 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();
}
 
源代码26 项目: io   文件: EsRetryOnParticularErrorTest.java
/**
 * 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);
    }
}
 
@Test
public void testWithNothingSet_result() throws IOException, InterruptedException {
    PowerMockito.mockStatic(DatadogUtilities.class);
    when(DatadogUtilities.currentTimeMillis()).thenReturn(0l);
    when(DatadogUtilities.getHostname(any(String.class))).thenReturn(null);

    ItemGroup parent = mock(ItemGroup.class);
    when(parent.getFullName()).thenReturn("parentFullName");

    Job job = mock(Job.class);
    when(job.getParent()).thenReturn(parent);
    when(job.getName()).thenReturn("jobName");

    Run run = mock(Run.class);
    when(run.getResult()).thenReturn(Result.FAILURE);
    when(run.getEnvironment(any(TaskListener.class))).thenReturn(null);
    when(run.getParent()).thenReturn(job);

    TaskListener listener = mock(TaskListener.class);
    BuildData bd = new BuildData(run, listener);
    DatadogEvent event = new BuildStartedEventImpl(bd);

    Assert.assertTrue(event.getHost() == null);
    Assert.assertTrue(event.getDate() == 0);
    Assert.assertTrue(event.getAggregationKey().equals("parentFullName/jobName"));
    Assert.assertTrue(event.getTags().size() == 2);
    Assert.assertTrue(event.getTags().get("job").contains("parentFullName/jobName"));
    Assert.assertTrue(event.getTags().get("result").contains("FAILURE"));
    Assert.assertTrue(event.getTitle().equals("Job parentFullName/jobName build #0 started on unknown"));
    Assert.assertTrue(event.getText().contains("User anonymous started the [job parentFullName/jobName build #0](unknown) (0.00 secs)"));
    Assert.assertTrue(event.getAlertType().equals(DatadogEvent.AlertType.INFO));
    Assert.assertTrue(event.getPriority().equals(DatadogEvent.Priority.LOW));
}
 
源代码28 项目: pxf   文件: PxfUserGroupInformationTest.java
@Test
public void testReloginFromKeytabNoopForNonKeytab() throws KerberosAuthException {
    user.setLogin(mockLoginContext);
    PowerMockito.mockStatic(KerberosUtil.class);
    when(KerberosUtil.hasKerberosKeyTab(subject)).thenReturn(false); // simulate no keytab for subject
    ugi = new UserGroupInformation(subject);
    ugi.setAuthenticationMethod(UserGroupInformation.AuthenticationMethod.KERBEROS);
    session = new LoginSession("config", "principal", "keytab", ugi, subject, 1);

    PxfUserGroupInformation.reloginFromKeytab(serverName, session);

    verifyZeroInteractions(mockLoginContext); // proves noop
}
 
源代码29 项目: gdx-fireapp   文件: AuthTest.java
@Override
public void setup() {
    super.setup();
    PowerMockito.mockStatic(FIRAuth.class);
    PowerMockito.mockStatic(FIRUser.class);
    PowerMockito.mockStatic(PtrFactory.class);
    PowerMockito.mockStatic(NSError.class);
    PowerMockito.mockStatic(Ptr.class);
    PowerMockito.mockStatic(NSURL.class);
    firAuth = PowerMockito.mock(FIRAuth.class);
    Mockito.when(FIRAuth.auth()).thenReturn(firAuth);
    consumer = Mockito.mock(Consumer.class);
    biConsumer = Mockito.mock(BiConsumer.class);
}
 
/********BugReporting*********/


    @Test
    public void givenShakingThreshold$setShakingThresholdForAndroid_whenQuery_thenShouldCallNativeApiWithShakingThreshold() {
        // given
        PowerMockito.mockStatic(BugReporting.class);
        int shakingThreshold = 30;
        // when
        bugReportingModule.setShakingThresholdForAndroid(shakingThreshold);
        // then
        PowerMockito.verifyStatic(VerificationModeFactory.times(1));
        BugReporting.setShakingThreshold(shakingThreshold);
    }