当前位置: 首页>>代码示例>>Java>>正文


Java PowerMockito.spy方法代码示例

本文整理汇总了Java中org.powermock.api.mockito.PowerMockito.spy方法的典型用法代码示例。如果您正苦于以下问题:Java PowerMockito.spy方法的具体用法?Java PowerMockito.spy怎么用?Java PowerMockito.spy使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.powermock.api.mockito.PowerMockito的用法示例。


在下文中一共展示了PowerMockito.spy方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: doGet_should_return_null_since_httpClient_execute_returned_with_unknown_response_code

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_null_since_httpClient_execute_returned_with_unknown_response_code()
        throws ClientProtocolException, IOException {

    String succResponse = "Test Response";

    CloseableHttpResponse httpResponse = PowerMockito
            .mock(CloseableHttpResponse.class);
    StatusLine statusLine = PowerMockito.mock(StatusLine.class);

    StringEntity entity = new StringEntity(succResponse);

    PowerMockito.spy(HttpUtils.class);

    try {
        PowerMockito.doReturn(mockHttpClient).when(HttpUtils.class,
                "initialize");
    } catch (Exception e1) {
        Assert.fail("Couldn't mock the HttpUtils.initialize method!", e1);
    }

    // and:
    PowerMockito.when(statusLine.getStatusCode()).thenReturn(600);
    PowerMockito.when(httpResponse.getEntity()).thenReturn(entity);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);
    HashMap<String, String> headers = new HashMap<String, String>();

    headers.put("test", "value");

    try {
        String response = HttpUtils.doGet("http://example.com", headers);

        Assert.assertNull(response);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
 
开发者ID:adobe,项目名称:stock-api-sdk,代码行数:41,代码来源:HttpUtilsTest.java

示例2: Date

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * isChangedメソッドですでに登録済みのキャッシュと変更が無い場合falseを返すこと.
 * @throws Exception 実行エラー
 */
@Test
public void isChangedメソッドですでに登録済みのキャッシュと変更が無い場合falseを返すこと() 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(PersoniumUnitConfig.class);
    PowerMockito.when(PersoniumUnitConfig.class, "isSchemaCacheEnabled").thenReturn(true);

    // 事前にキャッシュを登録する
    UserDataSchemaCache.cache(nodeId, schemaToCache);

    // isChanged?
    Map<String, Object> schemaToCacheNew = new HashMap<String, Object>();
    schemaToCacheNew.put("SchemaCacheTestKey001", "testValue");
    schemaToCacheNew.put("disabledTime", now);
    assertThat(UserDataSchemaCache.isChanged(nodeId, schemaToCacheNew)).isFalse();
}
 
开发者ID:personium,项目名称:personium-core,代码行数:31,代码来源:UserDataSchemaCacheTest.java

示例3: test_prepareJSRuntime_ShouldSendCorrectMessage

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test
public void test_prepareJSRuntime_ShouldSendCorrectMessage() throws Exception {
  final JSDebuggerWebSocketClient.JSDebuggerCallback cb =
    PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class);

  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());
  client.prepareJSRuntime(cb);
  PowerMockito.verifyPrivate(client).invoke("sendMessage", 0,
    "{\"id\":0,\"method\":\"prepareJSRuntime\"}");
}
 
开发者ID:qq565999484,项目名称:RNLearn_Project1,代码行数:11,代码来源:JSDebuggerWebSocketClientTest.java

示例4: test_executeJSCall_ShouldSendCorrectMessage

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test
public void test_executeJSCall_ShouldSendCorrectMessage() throws Exception {
  final JSDebuggerWebSocketClient.JSDebuggerCallback cb =
    PowerMockito.mock(JSDebuggerWebSocketClient.JSDebuggerCallback.class);

  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());

  client.executeJSCall("foo", "[1,2,3]", cb);
  PowerMockito.verifyPrivate(client).invoke("sendMessage", 0,
    "{\"id\":0,\"method\":\"foo\",\"arguments\":[1,2,3]}");
}
 
开发者ID:qq565999484,项目名称:RNLearn_Project1,代码行数:12,代码来源:JSDebuggerWebSocketClientTest.java

示例5: getPathSegmentList

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * ReadDeleteOnlyモードではない状態でPUTメソッドが実行された場合はPersoniumCoreExceptionが発生しないこと.
 * @throws Exception .
 */
@Test
public void ReadDeleteOnlyモードではない状態でPUTメソッドが実行された場合はPersoniumCoreExceptionが発生しないこと() throws Exception {
    PowerMockito.spy(ReadDeleteModeLockManager.class);
    PowerMockito.when(ReadDeleteModeLockManager.class, "isReadDeleteOnlyMode").thenReturn(false);
    List<PathSegment> pathSegment = getPathSegmentList(new String[] {"cell", "box", "odata", "entity" });
    try {
        PersoniumReadDeleteModeManager.checkReadDeleteOnlyMode(HttpMethod.PUT, pathSegment);
    } catch (PersoniumCoreException e) {
        fail(e.getMessage());
    }
}
 
开发者ID:personium,项目名称:personium-core,代码行数:16,代码来源:PersoniumReadDeleteModeManagerTest.java

示例6: setValueShouldChangeTheRegionEntryAddressToNewAddressAndDoesNothingIfOldAddressIsATokenAddress

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test
public void setValueShouldChangeTheRegionEntryAddressToNewAddressAndDoesNothingIfOldAddressIsATokenAddress() {
  // mock region entry
  OffHeapRegionEntry re = mock(OffHeapRegionEntry.class);

  long oldAddress = OffHeapRegionEntryHelper.REMOVED_PHASE1_ADDRESS;

  Token newValue = Token.REMOVED_PHASE2;
  long newAddress = OffHeapRegionEntryHelper.REMOVED_PHASE2_ADDRESS;

  // mock Chunk static methods - in-order to verify that release is never called
  PowerMockito.spy(OffHeapStoredObject.class);
  PowerMockito.doNothing().when(OffHeapStoredObject.class);
  OffHeapStoredObject.release(oldAddress);

  // mock region entry methods required for test
  when(re.getAddress()).thenReturn(oldAddress);
  when(re.setAddress(oldAddress, newAddress)).thenReturn(Boolean.TRUE);

  // invoke the method under test
  OffHeapRegionEntryHelper.setValue(re, newValue);

  // verify oldAddress is changed to newAddress
  verify(re, times(1)).setAddress(oldAddress, newAddress);

  // verify that release is never called as the old address is not on offheap
  PowerMockito.verifyStatic(never());
  OffHeapStoredObject.release(oldAddress);
}
 
开发者ID:ampool,项目名称:monarch,代码行数:30,代码来源:OffHeapRegionEntryHelperJUnitTest.java

示例7: MockMemcachedClient

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * UserDataSchemaのキャッシュを無効にしている場合キャッシュの取得削除を実行しても何も行わないこと.
 * @throws Exception 実行エラー
 */
@Test
public void UserDataSchemaのキャッシュを無効にしている場合キャッシュの取得削除を実行しても何も行わないこと() throws Exception {

    String nodeId = "node_YYYYYYYYYY1";
    Map<String, Object> schemaToCache = new HashMap<String, Object>();
    schemaToCache.put("SchemaCacheTestKey001", "testValue");

    // Mock用キャッシュクライアントを直接操作するためのキー
    String cacheKeyForMock = "userodata:" + nodeId;

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

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

    // 事前にキャッシュを登録
    UserDataSchemaCache.cache(nodeId, schemaToCache);
    assertThat(mockMemcachedClient.get(cacheKeyForMock, Map.class)).isEqualTo(schemaToCache);
    Map<String, Object> schemaFromCache = UserDataSchemaCache.get(nodeId);
    assertThat(schemaFromCache).isEqualTo(schemaFromCache);

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

    // キャッシュを取得できないこと
    schemaFromCache = UserDataSchemaCache.get(nodeId);
    assertThat(schemaFromCache).isNull();

    // キャッシュを削除できないこと
    UserDataSchemaCache.clear(nodeId);
    assertThat(mockMemcachedClient.get(cacheKeyForMock, Map.class)).isEqualTo(schemaToCache);
}
 
开发者ID:personium,项目名称:personium-core,代码行数:42,代码来源:UserDataSchemaCacheTest.java

示例8: makeEmpty_Normal_Type_ODataCollection

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Test makeEmpty().
 * normal.
 * Type is OData collection.
 * @throws Exception Unintended exception in test
 */
@Test
public void makeEmpty_Normal_Type_ODataCollection() throws Exception {
    // Mock settings
    davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null));

    doReturn(DavCmpFsImpl.TYPE_COL_ODATA).when(davCmpFsImpl).getType();

    doReturn("cellId").when(davCmpFsImpl).getCellId();
    Box box = mock(Box.class);
    doReturn(box).when(davCmpFsImpl).getBox();
    doReturn("boxId").when(box).getId();
    doReturn("nodeId").when(davCmpFsImpl).getId();

    Lock lock = mock(Lock.class);
    doNothing().when(lock).release();
    doReturn(lock).when(davCmpFsImpl).lockOData("cellId", "boxId", "nodeId");

    PowerMockito.whenNew(EsClient.class).withAnyArguments().thenReturn(null);
    PowerMockito.mockStatic(EsModel.class);
    PowerMockito.doReturn(null).when(EsModel.class, "type", "", "", "", 0, 0);

    CellDataAccessor cellDataAccessor = mock(CellDataAccessor.class);
    PowerMockito.doReturn(cellDataAccessor).when(EsModel.class, "cellData", "bundleName", "cellId");

    Cell cell = mock(Cell.class);
    doReturn("bundleName").when(cell).getDataBundleNameWithOutPrefix();
    davCmpFsImpl.cell = cell;
    doNothing().when(cellDataAccessor).bulkDeleteODataCollection("boxId", "nodeId");
    doNothing().when(davCmpFsImpl).doDelete();

    // Run method
    davCmpFsImpl.makeEmpty();
}
 
开发者ID:personium,项目名称:personium-core,代码行数:40,代码来源:DavCmpFsImplTest.java

示例9: test_onMessage_WithInvalidContentType_ShouldNotTriggerCallbacks

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test
public void test_onMessage_WithInvalidContentType_ShouldNotTriggerCallbacks() throws Exception {
  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());

  client.onMessage(ResponseBody.create(WebSocket.BINARY, "{\"replyID\":0, \"result\":\"OK\"}"));
  PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestSuccess", anyInt(), anyString());
  PowerMockito.verifyPrivate(client, never()).invoke("triggerRequestFailure", anyInt(), any());
}
 
开发者ID:qq565999484,项目名称:RNLearn_Project1,代码行数:9,代码来源:JSDebuggerWebSocketClientTest.java

示例10: MockMemcachedClient

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Cellのキャッシュを無効にしている場合キャッシュの登録を実行しても何も行わないこと.
 * @throws Exception 実行エラー
 */
@Test
public void Cellのキャッシュを無効にしている場合キャッシュの登録を実行しても何も行わないこと() throws Exception {

    String cellName = "cellCacheTestCell";
    Map<String, Object> cellToCache = new HashMap<String, Object>();
    cellToCache.put("CellCacheTestKey001", "testValue");

    // Mock用キャッシュクライアントを直接操作するためのキー
    String cacheKeyForMock = "cell:" + cellName;

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

    // キャッシュの設定を無効にする
    PowerMockito.spy(PersoniumUnitConfig.class);
    PowerMockito.when(PersoniumUnitConfig.class, "isCellCacheEnabled").thenReturn(false);

    // キャッシュ登録されないこと
    CellCache.cache(cellName, cellToCache);
    assertThat(mockMemcachedClient.get(cacheKeyForMock, Map.class)).isNull();

    // キャッシュを取得できないこと
    Map<String, Object> cellFromCache = CellCache.get(cellName);
    assertThat(cellFromCache).isNull();
}
 
开发者ID:personium,项目名称:personium-core,代码行数:32,代码来源:CellCacheTest.java

示例11: getNameFromRequestRelation_Normal_requestRelation_is_classURL

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Test getNameFromRequestRelation().
 * Normal test.
 * RequestRelation is ClassURL.
 * @throws Exception Unexpected error.
 */
@Test
public void getNameFromRequestRelation_Normal_requestRelation_is_classURL() throws Exception {
    cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl()));
    // --------------------
    // Test method args
    // --------------------
    String requestRelation = "personium-localunit:/dummyAppCell/__relation/__/dummyRelation";
    String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD;

    // --------------------
    // Mock settings
    // --------------------
    Cell mockCell = mock(Cell.class);
    cellCtlODataProducer.cell = mockCell;
    doReturn("http://personium").when(mockCell).getUnitUrl();

    PowerMockito.mockStatic(UriUtils.class);
    PowerMockito.doReturn("http://personium/dummyAppCell/__relation/__/dummyRelation").when(
            UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation);

    PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type);

    // --------------------
    // Expected result
    // --------------------
    String expectedRelationName = "dummyRelation";

    // --------------------
    // Run method
    // --------------------
    String actualRelationName = cellCtlODataProducer.getNameFromRequestRelation(requestRelation, type);

    // --------------------
    // Confirm result
    // --------------------
    assertThat(actualRelationName, is(expectedRelationName));
}
 
开发者ID:personium,项目名称:personium-core,代码行数:44,代码来源:CellCtlODataProducerTest.java

示例12: getNameFromRequestRelation_Normal_requestRelation_is_name

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Test getNameFromRequestRelation().
 * Normal test.
 * RequestRelation is Name.
 * @throws Exception Unexpected error.
 */
@Test
public void getNameFromRequestRelation_Normal_requestRelation_is_name() throws Exception {
    cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl()));
    // --------------------
    // Test method args
    // --------------------
    String requestRelation = "dummyRelation";
    String type = ReceivedMessage.TYPE_REQ_RELATION_BUILD;

    // --------------------
    // Mock settings
    // --------------------
    Cell mockCell = mock(Cell.class);
    cellCtlODataProducer.cell = mockCell;
    doReturn("http://personium").when(mockCell).getUnitUrl();

    PowerMockito.mockStatic(UriUtils.class);
    PowerMockito.doReturn(requestRelation).when(
            UriUtils.class, "convertSchemeFromLocalUnitToHttp", "http://personium", requestRelation);

    PowerMockito.doReturn(Common.PATTERN_RELATION_CLASS_URL).when(cellCtlODataProducer, "getRegexFromType", type);

    // --------------------
    // Expected result
    // --------------------
    String expectedRelationName = "dummyRelation";

    // --------------------
    // Run method
    // --------------------
    String actualRelationName = cellCtlODataProducer.getNameFromRequestRelation(requestRelation, type);

    // --------------------
    // Confirm result
    // --------------------
    assertThat(actualRelationName, is(expectedRelationName));
}
 
开发者ID:personium,项目名称:personium-core,代码行数:44,代码来源:CellCtlODataProducerTest.java

示例13: ByteArrayInputStream

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
@Test(groups = "Endpoints.getSearchFilesEndpoint")
public void getSearchFilesEndpoint_should_throw_stockexception_since_the_endpoint_properties_load_thrown_ioexception() {
    PowerMockito.spy(Endpoints.class);

    InputStream fakeResource = PowerMockito.spy(new ByteArrayInputStream(
            "foobar".getBytes()));

    try {
        PowerMockito.doThrow(new IOException()).when(fakeResource)
                .read(Mockito.any(byte[].class));
        PowerMockito.doReturn(fakeResource).when(Endpoints.class,
                "getResourceAsStream", Mockito.any(String.class));
    } catch (Exception e1) {
        Assert.fail(
                "Couldn't mock the Endpoints.getResourceAsStream method!",
                e1);
    }

    try {
        new Endpoints(Environment.STAGE);

        Assert.fail("Didn't expect the endpoints to get constructed without exception!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "Could not initialize the endpoints");
    }
}
 
开发者ID:adobe,项目名称:stock-api-sdk,代码行数:28,代码来源:EndpointsTest.java

示例14: move_Normal_Dest_DavNode_not_exists

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Test move().
 * Dest DavNode not exists.
 * @throws Exception Unintended exception in test
 */
@Test
public void move_Normal_Dest_DavNode_not_exists() throws Exception {
    String sourcePath = TEST_DIR_PATH + SOURCE_FILE;
    String destPath = TEST_DIR_PATH + DEST_FILE;
    File sourceFile = new File(sourcePath);
    File destFile = new File(destPath);
    try {
        sourceFile.createNewFile();
        // Test method args
        String etag = "\"1-1487652733383\"";
        String overwrite = "overwrite";
        DavDestination davDestination = mock(DavDestination.class);

        // Expected result
        boolean sourceFileExists = false;
        boolean destFileExists = true;
        FileInputStream sourceStream = new FileInputStream(sourceFile);
        String sourceFileMD5 = md5Hex(sourceStream);
        sourceStream.close();
        ResponseBuilder expected = Response.status(HttpStatus.SC_CREATED);
        expected.header(HttpHeaders.LOCATION, destPath);
        expected.header(HttpHeaders.ETAG, "\"1-1487652733383\"");

        // Mock settings
        davCmpFsImpl = PowerMockito.spy(DavCmpFsImpl.create("", null));
        Lock lock = mock(Lock.class);
        doNothing().when(lock).release();
        doReturn(lock).when(davCmpFsImpl).lock();
        doNothing().when(davCmpFsImpl).load();
        doReturn(true).when(davCmpFsImpl).exists();
        PowerMockito.doReturn(true).when(davCmpFsImpl, "matchesETag", anyString());
        File fsDir = mock(File.class);
        doReturn(sourceFile.toPath()).when(fsDir).toPath();
        Whitebox.setInternalState(davCmpFsImpl, "fsDir", fsDir);
        doReturn("\"1-1487652733383\"").when(davCmpFsImpl).getEtag();

        doNothing().when(davDestination).loadDestinationHierarchy();
        doNothing().when(davDestination).validateDestinationResource(anyString(), any(DavCmp.class));
        DavRsCmp davRsCmp = mock(DavRsCmp.class);
        AccessContext accessContext = PowerMockito.mock(AccessContext.class);
        doReturn(accessContext).when(davRsCmp).getAccessContext();
        doReturn(davRsCmp).when(davRsCmp).getParent();
        doNothing().when(davRsCmp).checkAccessContext(any(AccessContext.class), any(BoxPrivilege.class));
        doReturn(davRsCmp).when(davDestination).getDestinationRsCmp();
        DavCmpFsImpl destDavCmp = PowerMockito.mock(DavCmpFsImpl.class);
        File destDir = mock(File.class);
        doReturn(destFile.toPath()).when(destDir).toPath();
        Whitebox.setInternalState(destDavCmp, "fsDir", destDir);
        doReturn(false).when(destDavCmp).exists();
        doReturn(destDavCmp).when(davDestination).getDestinationCmp();
        doReturn(destPath).when(davDestination).getDestinationUri();

        // Run method
        ResponseBuilder actual = davCmpFsImpl.move(etag, overwrite, davDestination);

        // Confirm result
        assertThat(sourceFile.exists(), is(sourceFileExists));
        assertThat(destFile.exists(), is(destFileExists));
        FileInputStream destStream = new FileInputStream(destFile);
        assertThat(md5Hex(destStream), is(sourceFileMD5));
        assertThat(actual.build().getStatus(), is(expected.build().getStatus()));
        assertThat(actual.build().getMetadata().toString(), is(expected.build().getMetadata().toString()));

        destStream.close();
    } finally {
        sourceFile.delete();
        destFile.delete();
    }
}
 
开发者ID:personium,项目名称:personium-core,代码行数:75,代码来源:DavCmpFsImplTest.java

示例15: changeStatusAndUpdateRelation_Error_ValidCurrentStatus_is_false

import org.powermock.api.mockito.PowerMockito; //导入方法依赖的package包/类
/**
 * Test changeStatusAndUpdateRelation().
 * Error test.
 * ValidCurrentStatus is false.
 */
@SuppressWarnings("unchecked")
@Test
public void changeStatusAndUpdateRelation_Error_ValidCurrentStatus_is_false() {
    cellCtlODataProducer = PowerMockito.spy(new CellCtlODataProducer(new CellEsImpl()));
    // --------------------
    // Test method args
    // --------------------
    EdmEntitySet entitySet = EdmEntitySet.newBuilder().setName("dummyName").build();
    Map<String, Object> values = new HashMap<String, Object>();
    values.put("dummy", "dummy");
    OEntityKey originalKey = OEntityKey.create(values);
    String status = "status";

    // --------------------
    // Mock settings
    // --------------------
    Lock mockLock = mock(Lock.class);
    doNothing().when(mockLock).release();
    doReturn(mockLock).when(cellCtlODataProducer).lock();

    EntitySetDocHandler mockDocHandler = mock(EntitySetDocHandler.class);
    Map<String, Object> mockStaticFields = new HashMap<String, Object>();
    Map<String, Object> mockManyToOnelinkId = new HashMap<String, Object>();
    doReturn(mockStaticFields).when(mockDocHandler).getStaticFields();
    doReturn(mockManyToOnelinkId).when(mockDocHandler).getManyToOnelinkId();
    doReturn(mockDocHandler).when(cellCtlODataProducer).retrieveWithKey(entitySet, originalKey);

    Map<String, Object> mockConvertedStaticFields = new HashMap<String, Object>();
    mockConvertedStaticFields.put(ReceivedMessage.P_TYPE.getName(), "dummyType");
    mockConvertedStaticFields.put(ReceivedMessage.P_STATUS.getName(), "dummyStatus");
    mockConvertedStaticFields.put(ReceivedMessage.P_BOX_NAME.getName(), "dummyBoxName");
    // Change the return value according to the number of calls to getStaticFields
    when(mockDocHandler.getStaticFields()).thenReturn(
            mockStaticFields, mockConvertedStaticFields, mockConvertedStaticFields);
    doReturn(mockConvertedStaticFields).when(cellCtlODataProducer).convertNtkpValueToFields(entitySet,
            mockStaticFields, mockManyToOnelinkId);
    doNothing().when(mockDocHandler).setStaticFields(mockConvertedStaticFields);

    doReturn(true).when(cellCtlODataProducer).isValidMessageStatus("dummyType", status);
    doReturn(true).when(cellCtlODataProducer).isValidRelationStatus("dummyType", status);
    doReturn(false).when(cellCtlODataProducer).isValidCurrentStatus("dummyType", "dummyStatus");

    // --------------------
    // Expected result
    // --------------------
    // Nothing.

    // --------------------
    // Run method
    // --------------------
    try {
        cellCtlODataProducer.changeStatusAndUpdateRelation(entitySet, originalKey, status);
        fail("Not exception.");
    } catch (PersoniumCoreException e) {
        // --------------------
        // Confirm result
        // --------------------
        PersoniumCoreException expected = PersoniumCoreException.OData.REQUEST_FIELD_FORMAT_ERROR.params(
                ReceivedMessage.MESSAGE_COMMAND);
        assertThat(e.getStatus(), is(expected.getStatus()));
        assertThat(e.getCode(), is(expected.getCode()));
        assertThat(e.getMessage(), is(expected.getMessage()));
    }
}
 
开发者ID:personium,项目名称:personium-core,代码行数:70,代码来源:CellCtlODataProducerTest.java


注:本文中的org.powermock.api.mockito.PowerMockito.spy方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。