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


Java PowerMockito类代码示例

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


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

示例1: setup

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Before
public void setup() {

	// 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);

	stepExecution = spy(new EditCommentStep.Execution());

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

	final ResponseDataBuilder<Comment> builder = ResponseData.builder();
	when(jiraServiceMock.updateComment(anyString(), anyInt(), anyString())).thenReturn(builder.successful(true).code(200).message("Success").build());

	stepExecution.listener = taskListenerMock;
	stepExecution.envVars = envVarsMock;
	stepExecution.run = runMock;

	doReturn(jiraServiceMock).when(stepExecution).getJiraService(any());
}
 
开发者ID:ThoughtsLive,项目名称:jira-steps,代码行数:27,代码来源:EditCommentStepTest.java

示例2: testConvertJsonFromFileToObject_Success

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testConvertJsonFromFileToObject_Success() throws Exception {
    String filePath = "{}";
    Class<?> responseClass = GetEventResponseVO.class;

    Gson mockGson = PowerMockito.mock(Gson.class);
    FileInputStream mockFileInputStream = Mockito.mock(FileInputStream.class);
    InputStreamReader mockInputStreamReader = Mockito.mock(InputStreamReader.class);
    JsonReader mockJsonReader = Mockito.mock(JsonReader.class);

    PowerMockito.whenNew(FileInputStream.class).withArguments(Mockito.anyString()).thenReturn(mockFileInputStream);
    PowerMockito.whenNew(InputStreamReader.class).withArguments(Mockito.isA(InputStream.class), Mockito.anyString()).thenReturn(mockInputStreamReader);
    PowerMockito.whenNew(JsonReader.class).withArguments(Mockito.isA(Reader.class)).thenReturn(mockJsonReader);
    Mockito.when(mockGson.fromJson(Mockito.isA(JsonReader.class), Mockito.isA(Class.class))).thenReturn(ImmutableGetEventResponseVO.builder().build());
    Object responseObject = JsonUtils.convertJsonFromFileToObject(mockGson, filePath, responseClass);
    assertThat(responseObject).isNotNull();

    PowerMockito.verifyNew(FileInputStream.class, Mockito.times(1)).withArguments(Mockito.anyString());
    PowerMockito.verifyNew(InputStreamReader.class, Mockito.times(1)).withArguments(Mockito.isA(InputStream.class), Mockito.anyString());
    PowerMockito.verifyNew(JsonReader.class, Mockito.times(1)).withArguments(Mockito.isA(Reader.class));
    Mockito.verify(mockGson, Mockito.times(1)).fromJson(Mockito.isA(JsonReader.class), Mockito.isA(Class.class));
}
 
开发者ID:enjin,项目名称:Enjin-Coin-Java-SDK,代码行数:23,代码来源:JsonUtilsTest.java

示例3: testAddNotificationListenerWithEventMatcher

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testAddNotificationListenerWithEventMatcher() throws Exception {
    String auth = "xxxx";
    PlatformServiceImpl mockPlatformService = PowerMockito.mock(PlatformServiceImpl.class);
    PusherNotificationServiceImpl mockPusherNotificationService = PowerMockito.mock(PusherNotificationServiceImpl.class);

    PowerMockito.whenNew(PlatformServiceImpl.class).withParameterTypes(Config.class).withArguments(Mockito.isA(Config.class)).thenReturn(mockPlatformService);
    Mockito.when(mockPlatformService.getAuth(Mockito.isA(GetPlatformAuthRequestVO.class))).thenReturn(getPlatformAuthResponseVO);
    PowerMockito.whenNew(PusherNotificationServiceImpl.class).withParameterTypes(Notification.class).withArguments(Mockito.isA(Notification.class))
            .thenReturn(mockPusherNotificationService);
    Mockito.when(mockPusherNotificationService.initializeNotificationService(Mockito.isA(GetPlatformAuthDetailsResponseVO.class))).thenReturn(true);
    Mockito.doNothing().when(mockPusherNotificationService).setNotificationListeners(Mockito.isA(List.class));

    boolean result = notificationsAsyncService.initNotificationsServiceAsync(auth).get();
    assertThat(result).isTrue();

    EventMatcher eventMatcher = NotificationListenerRegistration.ALLOW_ALL_MATCHER;
    NotificationListenerRegistration addNotificationListenerAsyncRegistration = notificationsAsyncService.addNotificationListenerAsync(mockNotificationListener, eventMatcher).get();
    assertThat(addNotificationListenerAsyncRegistration).isNotNull();

    PowerMockito.verifyNew(PlatformServiceImpl.class).withArguments(Mockito.isA(Config.class));
    Mockito.verify(mockPlatformService, Mockito.times(1)).getAuth(Mockito.isA(GetPlatformAuthRequestVO.class));
    PowerMockito.verifyNew(PusherNotificationServiceImpl.class).withArguments(Mockito.isA(Notification.class));
    Mockito.verify(mockPusherNotificationService).setNotificationListeners(Mockito.isA(List.class));
}
 
开发者ID:enjin,项目名称:Enjin-Coin-Java-SDK,代码行数:27,代码来源:NotificationsAsyncServiceTest.java

示例4: doGet_should_return_string_response_since_httpClient_execute_returned_with_success

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test(groups = "HttpUtils.doGet")
public void doGet_should_return_string_response_since_httpClient_execute_returned_with_success()
        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(200);
    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.assertEquals(response, succResponse);
    } catch (StockException e) {
        Assert.fail("Exception occured while calling HttpUtils.doGet!", e);
    }
}
 
开发者ID:adobe,项目名称:stock-api-sdk,代码行数:41,代码来源:HttpUtilsTest.java

示例5: setup

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Before
public void setup() {

	// 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);

	stepExecution = spy(new EditVersionStep.Execution());

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

	final ResponseDataBuilder<Void> builder = ResponseData.builder();
	when(jiraServiceMock.updateVersion(any())).thenReturn(builder.successful(true).code(200).message("Success").build());

	stepExecution.listener = taskListenerMock;
	stepExecution.envVars = envVarsMock;
	stepExecution.run = runMock;

	doReturn(jiraServiceMock).when(stepExecution).getJiraService(any());
}
 
开发者ID:ThoughtsLive,项目名称:jira-steps,代码行数:27,代码来源:EditVersionStepTest.java

示例6: testGetTranslationMatrix

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testGetTranslationMatrix() throws Exception {
    Bitmap3DChar o = new Bitmap3DChar(string3D, chr, 0);

    PowerMockito.doAnswer(new Answer<Object>() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
            float[] matrix = (float[])invocation.getArguments()[0];

            for(int counter = 0; counter < matrix.length; counter++) {
                matrix[counter] = 2.0f;
            }
            return null;
        }
    }).when(
        Matrix.class, "translateM", o.translationMatrix, 0,
        10.0f + o.getPositionX(),
        11.0f + o.getPositionY(),
        12.0f + o.getPositionZ()
    );

    float[] expected = { 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f, 2.0f };
    assertArrayEquals(expected, o.getTranslationMatrix(), 0);
}
 
开发者ID:snada,项目名称:BitmapFontLoader,代码行数:25,代码来源:Bitmap3DCharTest.java

示例7: isMatchesBoxSchema_Normal_false

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
/**
 * Test isMatchesBoxSchema().
 * normal.
 * Return false.
 * @throws Exception Unintended exception in test
 */
@Test
public void isMatchesBoxSchema_Normal_false() throws Exception {
    // Test method args
    AccessContext ac = mock(AccessContext.class);

    // Mock settings
    boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null));

    doReturn(null).when(boxUrlRsCmp).getBox();
    doThrow(PersoniumCoreException.Auth.SCHEMA_MISMATCH).when(ac).checkSchemaMatches(null);

    // Expected result
    boolean expected = false;

    // Load methods for private
    Method method = BoxUrlRsCmp.class.getDeclaredMethod("isMatchesBoxSchema", AccessContext.class);
    method.setAccessible(true);

    // Run method
    boolean actual = (boolean) method.invoke(boxUrlRsCmp, ac);

    // Confirm result
    assertThat(actual, is(expected));
}
 
开发者ID:personium,项目名称:personium-core,代码行数:31,代码来源:BoxUrlRsCmpTest.java

示例8: testregisterClient

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testregisterClient() {
  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("clientName" , "ap");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/client/register").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:17,代码来源:ClientControllerTest.java

示例9: testsearchNote

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testsearchNote() {
  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<>();
  Map<String,Object> filterMap = new HashMap<>();
  filterMap.put(JsonKey.ID, "123");
  innerMap.put(JsonKey.FILTERS, filterMap);
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/note/search").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:19,代码来源:NotesControllerTest.java

示例10: testValidateAndLoad_WhenChainedToSfc_ThrowsValidationException

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testValidateAndLoad_WhenChainedToSfc_ThrowsValidationException() throws Exception {
    // Arrange
    final Long VALID_ID_WITH_SFC = 4l;
    DistributedAppliance da = createDA(VALID_ID_WITH_SFC, false);
    ServiceFunctionChain sfc = new ServiceFunctionChain("sfc-1", null);

    VirtualSystem vs = new VirtualSystem(null);
    vs.setName("vs-1");
    vs.setEncapsulationType(TagEncapsulationType.VLAN);
    vs.setServiceFunctionChains(Arrays.asList(sfc));
    da.addVirtualSystem(vs);
    PowerMockito.mockStatic(DistributedApplianceEntityMgr.class);
    PowerMockito.when(DistributedApplianceEntityMgr.isProtectingWorkload(da)).thenReturn(true);
    Mockito.when(this.em.find(Mockito.eq(DistributedAppliance.class), Mockito.eq(VALID_ID_WITH_SFC)))
            .thenReturn(da);
    this.exception.expect(VmidcBrokerValidationException.class);
    this.exception.expectMessage(
            String.format("The distributed appliance with name '%s' and id '%s' is currently protecting a workload",
                    da.getName(), da.getId()));

    // Act
    this.validator.validateAndLoad(createRequest(VALID_ID_WITH_SFC, false));
}
 
开发者ID:opensecuritycontroller,项目名称:osc-core,代码行数:25,代码来源:DeleteDistributedApplianceRequestValidatorTest.java

示例11: testcreateBatch

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testcreateBatch() {
  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(JsonKey.COURSE_ID , "org123");
  innerMap.put(JsonKey.NAME ,"IT BATCH");
  innerMap.put(JsonKey.ENROLLMENT_TYPE , JsonKey.INVITE_ONLY);
  SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
  Date currentdate = new Date();
  Calendar calendar = Calendar.getInstance();
  calendar.add(Calendar.DAY_OF_MONTH , 2);
  Date futureDate = calendar.getTime();
  innerMap.put(JsonKey.START_DATE , format.format(currentdate));
  innerMap.put(JsonKey.END_DATE , format.format(futureDate));
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/course/batch/create").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:26,代码来源:CourseBatchControllerTest.java

示例12: testupdatePageSection

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testupdatePageSection() {
  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("name" , "page1");
  innerMap.put("sectionDataType" , "section01");
  innerMap.put(JsonKey.ID , "001");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/update").method("PATCH");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:19,代码来源:PageControllerTest.java

示例13: testuploadFileService

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testuploadFileService() {
  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(JsonKey.DATA , "uploadFILEData".getBytes());
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/file/upload").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:17,代码来源:FileStorageControllerTest.java

示例14: testupdate

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
public void testupdate() {
  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 , "usergt78y4ry85464");
  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/update").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
开发者ID:project-sunbird,项目名称:sunbird-lms-service,代码行数:21,代码来源:DbOperationControllerTest.java

示例15: testCorrectBehaviourWhenTokenInSession

import org.powermock.api.mockito.PowerMockito; //导入依赖的package包/类
@Test
public void testCorrectBehaviourWhenTokenInSession() throws Exception {
    final CountDownLatch lock = new CountDownLatch(1);
    webContext.getSessionStore().set(webContext, CSRF_TOKEN, SESSION_UUID.toString())
        .thenRun(() -> lock.countDown());
    lock.await(1, TimeUnit.SECONDS);
    PowerMockito.mockStatic(UUID.class);
    when(UUID.randomUUID()).thenReturn(RANDOM_UUID);

    final CompletableFuture<String> future = new CompletableFuture<>();
    final DefaultAsyncCsrfTokenGenerator generator = new DefaultAsyncCsrfTokenGenerator();
    vertx.runOnContext(v -> {
        final CompletableFuture<String> csrfToken = generator.get(webContext);
        csrfToken.thenAccept(s -> future.complete(s));
    });
    final String retrievedCsrfToken = future.get();
    assertThat(retrievedCsrfToken, is(SESSION_UUID.toString()));
}
 
开发者ID:millross,项目名称:pac4j-async,代码行数:19,代码来源:DefaultAsyncCsrfTokenGeneratorTest.java


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