Java Code Examples for org.powermock.api.mockito.PowerMockito

The following are top voted examples for showing how to use org.powermock.api.mockito.PowerMockito. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: jira-steps   File: EditCommentStepTest.java   Source Code and License 7 votes vote down vote up
@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());
}
 
Example 2
Project: Enjin-Coin-Java-SDK   File: JsonUtilsTest.java   Source Code and License 7 votes vote down vote up
@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));
}
 
Example 3
Project: Enjin-Coin-Java-SDK   File: NotificationsAsyncServiceTest.java   Source Code and License 7 votes vote down vote up
@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));
}
 
Example 4
Project: stock-api-sdk   File: HttpUtilsTest.java   Source Code and License 6 votes vote down vote up
@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);
    }
}
 
Example 5
Project: BitmapFontLoader   File: Bitmap3DCharTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 6
Project: personium-core   File: BoxUrlRsCmpTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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));
}
 
Example 7
Project: sunbird-lms-service   File: ClientControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 8
Project: sunbird-lms-service   File: NotesControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 9
Project: osc-core   File: DeleteDistributedApplianceRequestValidatorTest.java   Source Code and License 6 votes vote down vote up
@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));
}
 
Example 10
Project: sunbird-lms-service   File: CourseBatchControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 11
Project: sunbird-lms-service   File: PageControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 12
Project: sunbird-lms-service   File: FileStorageControllerTest.java   Source Code and License 6 votes vote down vote up
@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());
}
 
Example 13
Project: sunbird-lms-service   File: DbOperationControllerTest.java   Source Code and License 6 votes vote down vote up
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());
}
 
Example 14
Project: pac4j-async   File: DefaultAsyncCsrfTokenGeneratorTest.java   Source Code and License 6 votes vote down vote up
@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()));
}
 
Example 15
Project: rskj   File: BridgeSerializationUtilsTest.java   Source Code and License 6 votes vote down vote up
@Test
public void desserializeFederation_wrongListSize() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_decode2(InnerListMode.NONE);

    StringBuilder sampleBuilder = new StringBuilder();
    sampleBuilder.append("04"); // Length of outer list
    sampleBuilder.append("02"); // Length of first element
    sampleBuilder.append("01"); // Length of second element
    sampleBuilder.append("01"); // Length of third element
    sampleBuilder.append("04"); // Length of fourth element
    sampleBuilder.append("1388"); // First element (creation date -> 5000 milliseconds from epoch)
    sampleBuilder.append("03"); // Second element (# of signatures required - 3)
    sampleBuilder.append("03"); // Third element
    sampleBuilder.append("aabbccdd"); // Fourth element
    byte[] sample = Hex.decode(sampleBuilder.toString());

    boolean thrown = false;
    try {
        BridgeSerializationUtils.deserializeFederation(sample, new Context(NetworkParameters.fromID(NetworkParameters.ID_REGTEST)));
    } catch (Exception e) {
        Assert.assertTrue(e.getMessage().contains("Expected 3 elements"));
        thrown = true;
    }
    Assert.assertTrue(thrown);
}
 
Example 16
Project: jira-steps   File: GetIssueLinkTypesStepTest.java   Source Code and License 6 votes vote down vote up
@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 GetIssueLinkTypesStep.Execution());

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

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

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

	doReturn(jiraServiceMock).when(stepExecution).getJiraService(any());
}
 
Example 17
Project: jira-steps-plugin   File: GetIssueLinkStepTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() throws IOException, InterruptedException {

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

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

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

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

  when(contextMock.get(Run.class)).thenReturn(runMock);
  when(contextMock.get(TaskListener.class)).thenReturn(taskListenerMock);
  when(contextMock.get(EnvVars.class)).thenReturn(envVarsMock);
}
 
Example 18
Project: jira-steps-plugin   File: GetCommentsStepTest.java   Source Code and License 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.getComments(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 19
Project: sunbird-lms-service   File: AssessmentControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testgetAssessment() {
  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("courseId" , "course-123");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/assessment/result/read").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
Example 20
Project: ULCRS   File: SessionControllerTest.java   Source Code and License 6 votes vote down vote up
@Before
public void init() throws Exception {
    MockitoAnnotations.initMocks(this);

    sessionControllerTest = new SessionController();

    directoryTest = new File(TEST_WORKSPACE_PATH);
    fileReaderTest = new FileReader(TEST_WORKSPACE_PATH + "2.json");

    Mockito.when(requestMock.params(Mockito.eq(":name"))).thenReturn("2");

    InputStream is = SessionController.class.getClassLoader().getResourceAsStream("mockSessionSchedule.json");
    JsonReader reader = new JsonReader(new InputStreamReader(is));
    Schedule schedule = gson.fromJson(reader, new TypeToken<Schedule>() {
    }.getType());
    String scheduleStrTest = gson.toJson(schedule);
    Mockito.when(requestMock.body()).thenReturn(scheduleStrTest);

    PowerMockito.whenNew(File.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH)).thenReturn(directoryTest);
    PowerMockito.whenNew(FileReader.class).withParameterTypes(String.class)
            .withArguments(Mockito.eq(WORKSPACE_PATH + "2.json")).thenReturn(fileReaderTest);
}
 
Example 21
Project: mug   File: RetryerBlockingTest.java   Source Code and License 6 votes vote down vote up
@Test public void interruptedDuringRetry() throws IOException, InterruptedException {
  Retryer retryer = new Retryer()
      .upon(IOException.class, Delay.ofMillis(100).exponentialBackoff(10, 1));
  IOException exception = new IOException();
  when(action.run()).thenThrow(exception);
  PowerMockito.doThrow(new InterruptedException()).when(Thread.class); Thread.sleep(100);
  Thread thread = PowerMockito.mock(Thread.class);
  PowerMockito.doReturn(thread).when(Thread.class); Thread.currentThread();

  assertException(IOException.class, () -> retryer.retryBlockingly(action::run))
      .isSameAs(exception);
  assertThat(exception.getSuppressed()).isEmpty();
  verify(action).run();
  verify(thread).interrupt();
  PowerMockito.verifyStatic(); Thread.sleep(100);
}
 
Example 22
Project: stock-api-sdk   File: LicenseHistoryTest.java   Source Code and License 6 votes vote down vote up
@Test(groups = "LicenseHistory.getNextLicenseHistory")
public void getNextLicenseHistory_should_return_valid_response() {
    try {

        LicenseHistory licenseHistory = new LicenseHistory(config, null,
                licenseHistoryRequest);

        PowerMockito.when(
                HttpUtils.doGet(Mockito.anyString(),
                        Matchers.<Map<String, String>> any())).thenReturn(
                TEST_RESPONSE);

        LicenseHistoryResponse response = licenseHistory.getNextLicenseHistory();
        LicenseHistoryTest.checkTestResponse(response);
        Assert.assertEquals(licenseHistory.currentLicenseHistoryPageIndex(), 0);
    } catch (StockException e) {
        Assert.fail("Didn't expect the StockException!", e);
    }
}
 
Example 23
Project: stock-api-sdk   File: LicenseHistoryTest.java   Source Code and License 6 votes vote down vote up
@Test(groups = "LicenseHistory.getNextLicenseHistory", expectedExceptions = { StockException.class }, expectedExceptionsMessageRegExp = "No more results available!")
public void getNextLicenseHistory_should_throw_exception_when_results_count_not_present_response()
        throws StockException {
    String responseString = "{}";

    licenseHistoryRequest.getSearchParams().setLimit(2);
    LicenseHistory licenseHistory = new LicenseHistory(config, "accessToken",
            licenseHistoryRequest);

    PowerMockito.when(
            HttpUtils.doGet(Mockito.anyString(),
                    Matchers.<Map<String, String>> any())).thenReturn(
                            responseString);

    LicenseHistoryResponse response = licenseHistory.getNextLicenseHistory();
    Assert.assertEquals(licenseHistory.getTotalLicenseHistoryFiles(),
            LicenseHistory.LICENSE_HISTORY_RETURN_ERROR);
    Assert.assertEquals(licenseHistory.getTotalLicenseHistoryPages(),
            LicenseHistory.LICENSE_HISTORY_RETURN_ERROR);
    Assert.assertEquals(licenseHistory.currentLicenseHistoryPageIndex(),
            LicenseHistory.LICENSE_HISTORY_RETURN_ERROR);
    Assert.assertNull(response.getNbResults());
    licenseHistory.getNextLicenseHistory();
}
 
Example 24
Project: monarch   File: DataTypeJUnitTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDataSerializableFixedIDInt() throws IOException, ClassNotFoundException {
  Integer someDSFIDInt = new Integer(1);

  PowerMockito.mockStatic(DSFIDFactory.class);
  when(DSFIDFactory.create(eq(someDSFIDInt), any())).thenReturn(someDSFIDInt);
  DSFIDFactory.create(someDSFIDInt, null);

  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  DataOutputStream out = new DataOutputStream(baos);
  DataSerializer.writeByte(DSCODE.DS_FIXED_ID_INT, out);
  DataSerializer.writeInteger(someDSFIDInt, out);
  byte[] bytes = baos.toByteArray();
  String type = DataType.getDataType(bytes);
  assertEquals("org.apache.geode.internal.DataSerializableFixedID:" + Integer.class.getName(),
      type);
}
 
Example 25
Project: sunbird-lms-service   File: EmailServiceControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testsendMailWithInvalidRequestData() {
  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.ORG_NAME , "org123");
  innerMap.put(JsonKey.SUBJECT , "");
  innerMap.put(JsonKey.BODY , "");
  List<String> recepeintsEmails = new ArrayList<>();
  recepeintsEmails.add("abc");
  List<String> receipeintUserIds = new ArrayList<>();
  receipeintUserIds.add("user001");
  innerMap.put("recipientEmails" , recepeintsEmails);
  innerMap.put("recipientUserIds" , receipeintUserIds);
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/notification/email").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(400, result.status());
}
 
Example 26
Project: jwala   File: ResourceServiceImplTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setup() throws Exception {
    System.setProperty(ApplicationProperties.PROPERTIES_ROOT_PATH, new File(".").getAbsolutePath() + "/src/test/resources");
    PowerMockito.mockStatic(JwalaUtils.class);
    PowerMockito.when(JwalaUtils.getHostAddress("testServer")).thenReturn(Inet4Address.getLocalHost().getHostAddress());
    PowerMockito.when(JwalaUtils.getHostAddress("testServer2")).thenReturn(Inet4Address.getLocalHost().getHostAddress());

    // It is good practice to start with a clean sheet of paper before each test that is why resourceService is
    // initialized here. This makes sure that unrelated tests don't affect each other.
    MockitoAnnotations.initMocks(this);
    reset(Config.mockHistoryFacadeService);
    reset(Config.mockJvmPersistenceService);
    reset(Config.mockWebServerPersistenceService);
    reset(Config.mockGroupPesistenceService);
    reset(Config.mockAppPersistenceService);

    when(Config.mockJvmPersistenceService.findJvmByExactName(eq("someJvm"))).thenReturn(mock(Jvm.class));
    when(Config.mockRepositoryService.upload(anyString(), any(InputStream.class))).thenReturn("thePath");
}
 
Example 27
Project: RexCord   File: PauseCommandTest.java   Source Code and License 6 votes vote down vote up
@Test
public void playlistSize_more_than_zero_and_unpaused_then_rexCord_sendMessage_UnpausedSong() throws Exception {

    // arrange on setUp
    AudioPlayer mockAudioPlayer = mock(AudioPlayer.class);
    when(mockAudioPlayer.getPlaylistSize()).thenReturn(1);
    when(mockAudioPlayer.isPaused()).thenReturn(false);

    PowerMockito.mockStatic(AudioPlayer.class);
    when(AudioPlayer.getAudioPlayerForGuild(mockEvent.getGuild())).thenReturn(mockAudioPlayer);

    // act
    command.runCommand(mockEvent, "");

    // assert
    verify(mockAudioPlayer).togglePause();
    verify(rexCord).sendMessage(mockIChannel, "Unpaused song.");
}
 
Example 28
Project: RexCord   File: SkipCommandTest.java   Source Code and License 6 votes vote down vote up
@Test
public void playlistSize_more_than_zero_and_then_rexCord_sendMessage_SkippedSong() throws Exception {

    // arrange on setUp
    AudioPlayer mockAudioPlayer = mock(AudioPlayer.class);
    when(mockAudioPlayer.getPlaylistSize()).thenReturn(1);

    PowerMockito.mockStatic(AudioPlayer.class);
    when(AudioPlayer.getAudioPlayerForGuild(mockEvent.getGuild())).thenReturn(mockAudioPlayer);

    // act
    command.runCommand(mockEvent, "");

    // assert
    verify(mockAudioPlayer).skip();
    verify(rexCord).sendMessage(mockIChannel, "Skipped song.");
}
 
Example 29
Project: sunbird-lms-service   File: PageControllerTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testcreatePageSection() {
  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");
  requestMap.put(JsonKey.REQUEST , innerMap);
  String data = mapToJson(requestMap);

  JsonNode json = Json.parse(data);
  RequestBuilder req = new RequestBuilder().bodyJson(json).uri("/v1/page/section/create").method("POST");
  req.headers(headerMap);
  Result result = route(req);
  assertEquals(200, result.status());
}
 
Example 30
Project: mirrorgate-jenkins-builds-collector   File: MirrorGateListenerHelperTest.java   Source Code and License 6 votes vote down vote up
@Before
@Override
public void setUp() {
    PowerMockito.mockStatic(Jenkins.class);
    PowerMockito.when(Jenkins.getInstance()).thenReturn(jenkins);
    PowerMockito.when(jenkins.getDescriptorByType(any()))
            .thenReturn(descriptor);

    PowerMockito.when(MirrorGateUtils.getMirrorGateAPIUrl())
            .thenReturn(MIRRORGATE_URL);
    PowerMockito.when(MirrorGateUtils.getUsernamePasswordCredentials())
            .thenReturn(null);
    PowerMockito.when(MirrorGateUtils.getExtraUrls())
            .thenReturn(EXTRA_URL);

    when(helper.getMirrorGateService()).thenReturn(service);
}
 
Example 31
Project: qpp-conversion-tool   File: JwtAuthorizationFilterTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testDoFilterInternalWithInvalidOrgName() throws IOException, ServletException {
	JwtPayloadHelper payload = new JwtPayloadHelper()
			.withName("invalid-name")
			.withOrgType(ORG_TYPE);

	request.addHeader("Authorization", JwtTestHelper.createJwt(payload));
	JwtAuthorizationFilter testJwtAuthFilter = new JwtAuthorizationFilter(authenticationManager);

	PowerMockito.mockStatic(SecurityContextHolder.class);
	SecurityContext mockSecurityContext = PowerMockito.mock(SecurityContext.class);

	PowerMockito.when(SecurityContextHolder.getContext()).thenReturn(mockSecurityContext);

	testJwtAuthFilter.doFilterInternal(request, response, filterChain);

	verify(filterChain, times(1)).doFilter(any(MockHttpServletRequest.class), any(MockHttpServletResponse.class));
	verify(SecurityContextHolder.getContext(), times(0)).setAuthentication(any(UsernamePasswordAuthenticationToken.class));
}
 
Example 32
Project: jira-steps-plugin   File: EditComponentStepTest.java   Source Code and License 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.updateComponent(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 33
Project: Enjin-Coin-Java-SDK   File: PusherNotificationServiceTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testInitializeNotificationService_Success() throws Exception {
    PusherOptions mockPusherOptions = PowerMockito.mock(PusherOptions.class);
    Pusher mockPusher               = PowerMockito.mock(Pusher.class);
    Channel mockChannel             = Mockito.mock(Channel.class);

    PowerMockito.whenNew(PusherOptions.class).withNoArguments().thenReturn(mockPusherOptions);
    Mockito.when(mockPusherOptions.setCluster(Mockito.anyString())).thenReturn(mockPusherOptions);
    Mockito.when(mockPusherOptions.setActivityTimeout(Mockito.anyLong())).thenReturn(mockPusherOptions);
    PowerMockito.whenNew(Pusher.class).withArguments(Mockito.anyString(), Mockito.isA(PusherOptions.class)).thenReturn(mockPusher);
    Mockito.doNothing().when(mockPusher).connect(Mockito.isA(ConnectionEventListener.class), Mockito.isA(ConnectionState.class));
    Mockito.when(mockPusher.subscribe(Mockito.anyString())).thenReturn(mockChannel);
    Mockito.doNothing().when(mockChannel).bind(Mockito.anyString(), Mockito.isA(SubscriptionEventListener.class));

    boolean result = pusherNotificationService.initializeNotificationService(getPlatformAuthDetailsResponseVO);
    assertThat(result).isTrue();

    PowerMockito.verifyNew(PusherOptions.class).withNoArguments();
    Mockito.verify(mockPusherOptions, Mockito.times(1)).setCluster(Mockito.anyString());
    Mockito.verify(mockPusherOptions, Mockito.times(1)).setActivityTimeout(Mockito.anyLong());
    PowerMockito.verifyNew(Pusher.class).withArguments(Mockito.anyString(), Mockito.isA(PusherOptions.class));
    Mockito.verify(mockPusher).connect(Mockito.isA(ConnectionEventListener.class), Mockito.isA(ConnectionState.class));
    Mockito.verify(mockPusher, Mockito.times(1)).subscribe(Mockito.anyString());
    Mockito.verify(mockChannel, Mockito.atLeastOnce()).bind(Mockito.anyString(), Mockito.isA(SubscriptionEventListener.class));
}
 
Example 34
Project: juraclient   File: UraClientTest.java   Source Code and License 6 votes vote down vote up
@Test
public void getTripsTowardsTest() throws Exception {
    /* Mock the HTTP call */
    URL mockURL = PowerMockito.mock(URL.class);
    PowerMockito.whenNew(URL.class).withAnyArguments().thenReturn(mockURL);
    PowerMockito.when(mockURL.openStream())
            .thenReturn(getClass().getResourceAsStream("instant_V1_trips_towards.txt"));

    /* List stops and verify some values */
    List<Trip> trips = new UraClient("mocked").towards("Marble Arch").getTrips();
    assertThat(trips, hasSize(10));

    PowerMockito.when(mockURL.openStream())
            .thenReturn(getClass().getResourceAsStream("instant_V1_trips_stop_towards.txt"));
    trips = new UraClient("mocked").forStops("156").towards("Marble Arch").getTrips();
    assertThat(trips, hasSize(17));
    assertThat(trips.stream().filter(t -> !t.getStop().getId().equals("156")).findAny(), is(Optional.empty()));
}
 
Example 35
Project: dds-examples   File: RoutingServiceEntitiesFilterTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testIgnoreSubscriptionFalse() throws Exception {
  // setup mock for participant data
  ParticipantBuiltinTopicData participantBuiltinTopicData = mock(ParticipantBuiltinTopicData.class);
  {
    ServiceQosPolicy serviceQosPolicy = PowerMockito.mock(ServiceQosPolicy.class);
    serviceQosPolicy.kind = ServiceQosPolicyKind.NO_SERVICE_QOS;
    Whitebox.setInternalState(participantBuiltinTopicData, "service", serviceQosPolicy);
  }
  PowerMockito.whenNew(ParticipantBuiltinTopicData.class).withAnyArguments().thenReturn(participantBuiltinTopicData);

  // setup mock for topic helper
  PowerMockito.mockStatic(BuiltinTopicHelper.class);
  when(BuiltinTopicHelper.getParticipantBuiltinTopicData(
      any(DomainParticipant.class), any(BuiltinTopicKey_t.class))
  ).thenReturn(participantBuiltinTopicData);

  // setup mock for subscription topic data
  SubscriptionBuiltinTopicData data = mock(SubscriptionBuiltinTopicData.class);
  BuiltinTopicKey_t key = PowerMockito.mock(BuiltinTopicKey_t.class);
  Whitebox.setInternalState(data, "participant_key", key);

  // setup mock for instance handle
  InstanceHandle_t instanceHandle = mock(InstanceHandle_t.class);

  // call ignore subscription
  assertFalse(filter.ignoreSubscription(domainParticipant, instanceHandle, data));
}
 
Example 36
Project: prisonPicks   File: PickCommandsTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp()
{
    MockitoAnnotations.initMocks(this);

    // Initialize the Mock server.
    JavaPluginLoader mockPluginLoader = new JavaPluginLoader(mockServer);
    Whitebox.setInternalState(mockPluginLoader, "server", mockServer);
    when(mockServer.getName()).thenReturn("TestBukkit");
    Logger.getLogger("Minecraft").setParent(TestUtil.logger);
    when(mockServer.getLogger()).thenReturn(TestUtil.logger);

     // Return a fake PDF file.
    PluginDescriptionFile pdf = PowerMockito.spy(new PluginDescriptionFile("PrisonPicks", "1.3.4-Test",
            "com.philderbeast.prisonpicks.PrisonPicks"));
    when(pdf.getAuthors()).thenReturn(new ArrayList<String>());

    pickCommands = new PickCommands();

    // MOCKS BELOW HERE
    when(player.getUniqueId()).thenReturn(UUID.fromString("e3078d5d-8943-420c-8366-4aa51e212df3"));
    when(player.getInventory()).thenReturn(playerInventory);

    PowerMockito.mockStatic(Bukkit.class);
    when(Bukkit.getPlayer(anyString())).thenReturn(player);
    when(Bukkit.getItemFactory()).thenReturn(itemFactory);

    when(itemFactory.getItemMeta(Material.DIAMOND_PICKAXE)).thenReturn(itemMeta);

}
 
Example 37
Project: personium-core   File: BoxUrlRsCmpTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test checkAccessContext().
 * error.
 * Token without access authority.
 * Access type invalid.
 * @throws Exception Unintended exception in test
 */
@Test
public void checkAccessContext_Error_not_has_privilege_type_invalid() throws Exception {
    // Test method args
    AccessContext ac = mock(AccessContext.class);
    Privilege privilege = null;

    // Mock settings
    boxUrlRsCmp = PowerMockito.spy(new BoxUrlRsCmp(new CellRsCmp(null, null, null), null, null, null));
    doReturn(AcceptableAuthScheme.BEARER).when(boxUrlRsCmp).getAcceptableAuthScheme();

    doReturn(false).when(ac).isUnitUserToken();
    doReturn("testSchema").when(ac).getSchema();
    PowerMockito.doReturn(false).when(boxUrlRsCmp, "isMatchesBoxSchema", ac);

    doReturn("none").when(boxUrlRsCmp).getConfidentialLevel();
    doReturn(null).when(boxUrlRsCmp).getBox();
    doNothing().when(ac).checkSchemaAccess("none", null, AcceptableAuthScheme.BEARER);

    doNothing().when(ac).updateBasicAuthenticationStateForResource(null);

    doReturn(false).when(boxUrlRsCmp).hasPrivilege(ac, privilege);

    doReturn(AccessContext.TYPE_INVALID).when(ac).getType();
    doThrow(PersoniumCoreException.Server.UNKNOWN_ERROR).when(ac).throwInvalidTokenException(
            AcceptableAuthScheme.BEARER);

    // Run method
    try {
        boxUrlRsCmp.checkAccessContext(ac, privilege);
        fail("Not throws exception.");
    } catch (PersoniumCoreException e) {
        // Confirm result
        assertThat(e.getCode(), is(PersoniumCoreException.Server.UNKNOWN_ERROR.getCode()));
        assertThat(e.getMessage(), is(PersoniumCoreException.Server.UNKNOWN_ERROR.getMessage()));
    }
}
 
Example 38
Project: stock-api-sdk   File: HttpUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test(groups = "HttpUtils.doGet")
public void doGet_should_throw_stockexception_since_httpClient_execute_returned_with_internal_server_error()
        throws ClientProtocolException, IOException {

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

    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(500);
    PowerMockito.when(httpResponse.getStatusLine()).thenReturn(statusLine);

    PowerMockito.when(mockHttpClient.execute(Mockito.any(HttpGet.class)))
            .thenReturn(httpResponse);

    try {
        HttpUtils.doGet("http://example.com", null);

        Assert.fail("Expected the StockException since the httpclient.execute returned with bad request!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "API returned with Server Error");
        Assert.assertEquals(e.getCode(), 500);
    }
}
 
Example 39
Project: Enjin-Coin-Java-SDK   File: JsonUtilsTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testConvertJsonToObject_Success() throws Exception {
    String jsonString = "{}";
    Class<?> responseClass = GetEventResponseVO.class;

    Gson mockGson = PowerMockito.mock(Gson.class);

    Mockito.when(mockGson.fromJson(Mockito.anyString(), Mockito.isA(Class.class))).thenReturn(ImmutableGetEventResponseVO.builder().build());
    Object responseObject = JsonUtils.convertJsonToObject(mockGson, jsonString, responseClass);
    assertThat(responseObject).isNotNull();

    Mockito.verify(mockGson, Mockito.times(1)).fromJson(Mockito.anyString(), Mockito.isA(Class.class));
}
 
Example 40
Project: jira-steps   File: EditVersionStepTest.java   Source Code and License 5 votes vote down vote up
@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());
}
 
Example 41
Project: personium-core   File: UserDataSchemaCacheTest.java   Source Code and License 5 votes vote down vote up
/**
 * 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("SchemaCacheTestKey002", "testValue");
    schemaToCacheNew.put("disabledTime", now);
    assertThat(UserDataSchemaCache.isChanged(nodeId, schemaToCacheNew)).isFalse();
}
 
Example 42
Project: BitmapFontLoader   File: AngelCodeXmlLoaderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testHorizontalSpacing() throws Exception {
    PowerMockito.when(parser, "getName").thenReturn("info");

    BitmapFont font = new BitmapFont();
    AngelCodeXmlLoader.load(font, stream);
    assertEquals(8, font.getHorizontalSpacing());
}
 
Example 43
Project: Enjin-Coin-Java-SDK   File: JsonRpcUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testSendJsonRpcRequest_SuccessResponse() throws Exception {
    String url = "http://localhost:8080/Identities.php";
    Class<?> responseClass = GetEventDataVO.class;
    String method = "method1";
    Map<String, Object> params = new HashMap<>();
    params.put("param1", "value1");
    CreateIdentityRequestVO createIdentityRequestVO = ImmutableCreateIdentityRequestVO.builder().setAuth("auth").build();
    String responseJson = JsonUtils.convertObjectToJson(GsonUtils.GSON, createIdentityRequestVO);

    PowerMockito.mockStatic(JsonUtils.class);
    URL mockUrl = PowerMockito.mock(URL.class);
    JSONRPC2Session mockJSONRPC2Session = PowerMockito.mock(JSONRPC2Session.class);
    JSONRPC2SessionOptions mockOptions = Mockito.mock(JSONRPC2SessionOptions.class);
    JSONRPC2Request mockJSONRPC2Request = Mockito.mock(JSONRPC2Request.class);
    JSONRPC2Response mockJSONRPC2Response = Mockito.mock(JSONRPC2Response.class);

    PowerMockito.whenNew(URL.class).withArguments(Mockito.anyString()).thenReturn(mockUrl);
    PowerMockito.whenNew(JSONRPC2Session.class).withArguments(Mockito.isA(URL.class)).thenReturn(mockJSONRPC2Session);
    Mockito.when(mockJSONRPC2Session.getOptions()).thenReturn(mockOptions);
    PowerMockito.whenNew(JSONRPC2Request.class).withParameterTypes(String.class, Map.class, Object.class).withArguments(Mockito.anyString(), Mockito.isA(Map.class), Mockito.any()).thenReturn(mockJSONRPC2Request);
    Mockito.when(mockJSONRPC2Session.send(Mockito.isA(JSONRPC2Request.class))).thenReturn(mockJSONRPC2Response);
    Mockito.when(mockJSONRPC2Response.indicatesSuccess()).thenReturn(true);
    Mockito.when(mockJSONRPC2Response.getResult()).thenReturn(responseJson);
    PowerMockito.when(JsonUtils.convertJsonToObject(Mockito.isA(Gson.class), Mockito.anyString(), Mockito.isA(Class.class))).thenReturn(createIdentityRequestVO);

    jsonRpcUtils = new JsonRpcUtils();
    Object responseObject = jsonRpcUtils.sendJsonRpcRequest(url, responseClass, method, params);
    assertThat(responseObject).isNotNull();

    PowerMockito.verifyNew(URL.class, Mockito.times(1)).withArguments(Mockito.anyString());
    PowerMockito.verifyNew(JSONRPC2Session.class, Mockito.times(1)).withArguments(Mockito.isA(URL.class));
    Mockito.verify(mockJSONRPC2Session, Mockito.times(1)).getOptions();
    PowerMockito.verifyNew(JSONRPC2Request.class, Mockito.times(1)).withArguments(Mockito.anyString(), Mockito.isA(Map.class), Mockito.any());
    Mockito.verify(mockJSONRPC2Session, Mockito.times(1)).send(Mockito.isA(JSONRPC2Request.class));
    Mockito.verify(mockJSONRPC2Response, Mockito.times(1)).indicatesSuccess();
    Mockito.verify(mockJSONRPC2Response, Mockito.times(1)).getResult();
}
 
Example 44
Project: rskj   File: BridgeSerializationUtilsTest.java   Source Code and License 5 votes vote down vote up
@Test
public void desserializeMapOfHashesToLong_nonEmptyOddSize() throws Exception {
    PowerMockito.mockStatic(RLP.class);
    mock_RLP_decode2_forMapOfHashesToLong();

    boolean thrown = false;
    try {
        byte[] sample = new byte[]{(byte)'b', 7, (byte)'d', 76, (byte) 'a'};
        BridgeSerializationUtils.deserializeMapOfHashesToLong(sample);
    } catch (RuntimeException e) {
        thrown = true;
    }
    Assert.assertTrue(thrown);
}
 
Example 45
Project: Enjin-Coin-Java-SDK   File: TransactionRequestsServiceTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings({ "unchecked", "serial" })
@Test
public void testGetTransactionRequest_Success() throws Exception {

    GetTransactionRequestRequestVO getTransactionRequestRequestVO = ImmutableGetTransactionRequestRequestVO.builder()
            .setAuth("xxxxxxxx")
            .setIdentityMap(new HashMap<String, Object>() {{
                put("identity_id", "12345");
            }})
            .setAppId("123")
            .setRecipientMap(new HashMap<String, Object>() {{
                put("identity_id", "12345");
            }})
            .setType("buy")
            .setAfterTxrId("1234567")
            .setLimit("50")
            .setCurrency("23456")
            .build();

    GetTransactionRequestResponseVO returnedGetTransactionRequestResponseVO = ImmutableGetTransactionRequestResponseVO.builder().build();
    GetTransactionRequestResponseVO[] returnedGetTransactionRequestResponseArray = new GetTransactionRequestResponseVO[] {returnedGetTransactionRequestResponseVO};

    JsonRpcUtils mockJsonRpcUtils = PowerMockito.mock(JsonRpcUtils.class);
    PowerMockito.whenNew(JsonRpcUtils.class).withNoArguments().thenReturn(mockJsonRpcUtils);
    Mockito.when(mockJsonRpcUtils.sendJsonRpcRequest(Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.isA(Map.class))).thenReturn(returnedGetTransactionRequestResponseArray);

    transactionRequestsService = new TransactionRequestsServiceImpl(enjinConfig);
    GetTransactionRequestResponseVO[] getTransactionRequestResponseVO = transactionRequestsService.getTransactionRequest(getTransactionRequestRequestVO);
    assertThat(getTransactionRequestResponseVO).isNotNull();

    PowerMockito.verifyNew(JsonRpcUtils.class, Mockito.times(1)).withNoArguments();
    Mockito.verify(mockJsonRpcUtils, Mockito.times(1)).sendJsonRpcRequest(Mockito.anyString(), Mockito.any(), Mockito.anyString(), Mockito.isA(Map.class));
}
 
Example 46
Project: personium-core   File: UserDataSchemaCacheTest.java   Source Code and License 5 votes vote down vote up
/**
 * isChangedメソッドでMemcachedへの接続に失敗した場合Trueを返すこと.
 * @throws Exception テスト中の例外
 */
@SuppressWarnings("unchecked")
@Test
public void isChangedメソッドでMemcachedへの接続に失敗した場合Trueを返すこと() throws Exception {
    String nodeId = "nodeId";
    Map<String, Object> data = new HashMap<String, Object>();
    data.put("testKey", "testValue");

    // MemcachedClientのモックを作成(getしたときにMemchachedClientExceptionをthrowするモック)
    Constructor<MemcachedClient> c = MemcachedClient.class.getDeclaredConstructor();
    c.setAccessible(true);
    MemcachedClient mockMemcachedClient = Mockito.spy(c.newInstance());
    Mockito.doThrow(new MemcachedClientException(null)).when(mockMemcachedClient)
            .get(Mockito.anyString(), Mockito.any(Class.class));

    // UserDataSchemaCacheのモックを作成(MemcachedClientのモックを使用するモック)
    PowerMockito.spy(UserDataSchemaCache.class);
    PowerMockito.when(UserDataSchemaCache.class, "getMcdClient").thenReturn(mockMemcachedClient);

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

    // isChangedメソッドのテスト
    boolean isChanged = UserDataSchemaCache.isChanged(nodeId, data);
    // キャッシュが有効の場合、trueが返却される
    assertEquals(true, isChanged);
}
 
Example 47
Project: GitHub   File: ProducerSequenceFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testLocalImageFileFullPrefetch() {
  PowerMockito.when(mImageRequest.getSourceUriType())
      .thenReturn(SOURCE_TYPE_LOCAL_IMAGE_FILE);
  Producer<Void> producer =
      mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
  assertSame(
      producer,
      mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
          mProducerSequenceFactory.mLocalImageFileFetchSequence));
}
 
Example 48
Project: osc-core   File: AddVirtualizationConnectorServiceRequestValidatorTest.java   Source Code and License 5 votes vote down vote up
@Before
public void testInitialize() throws EncryptionException {
    MockitoAnnotations.initMocks(this);

    PowerMockito.mockStatic(StaticRegistry.class);
    when(StaticRegistry.encryptionApi()).thenReturn(this.encryption);
}
 
Example 49
Project: RNLearn_Project1   File: JSDebuggerWebSocketClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void test_onMessage_With_Null_Error_ShouldTriggerRequestSuccess() throws Exception {
  JSDebuggerWebSocketClient client = PowerMockito.spy(new JSDebuggerWebSocketClient());

  client.onMessage(ResponseBody.create(WebSocket.TEXT, "{\"replyID\":0, \"error\":null}"));
  PowerMockito.verifyPrivate(client).invoke("triggerRequestSuccess", anyInt(), anyString());
}
 
Example 50
Project: personium-core   File: UnitCtlResourceTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test checkAccessContextPerEntity().
 * normal.
 * Type is UnitUser and owner equeal subject.
 * @throws Exception Unintended exception in test
 */
@Test
public void checkAccessContextPerEntity_Normal_type_unituser_owner_equal_subject() throws Exception {
    // Test method args
    AccessContext ac = PowerMockito.mock(AccessContext.class);
    OEntityWrapper oew = PowerMockito.mock(OEntityWrapper.class);

    // Mock settings
    UriInfo uriInfo = mock(UriInfo.class);
    URI uri = new URI("");
    doReturn(uri).when(uriInfo).getBaseUri();
    unitCtlResource = spy(new UnitCtlResource(ac, uriInfo));

    Map<String, Object> meta = new HashMap<>();
    meta.put("Owner", "personium-localunit:/admincell/#admin");
    doReturn(meta).when(oew).getMetadata();

    doReturn("http://personiumunit/").when(ac).getBaseUri();
    PowerMockito.mockStatic(UriUtils.class);
    PowerMockito.doReturn("http://personiumunit/admincell/#admin").when(UriUtils.class,
            "convertSchemeFromLocalUnitToHttp", "http://personiumunit/", "personium-localunit:/admincell/#admin");

    doReturn(AccessContext.TYPE_UNIT_USER).when(ac).getType();

    doReturn("http://personiumunit/admincell/#admin").when(ac).getSubject();

    // Expected result
    // None.

    // Run method
    unitCtlResource.checkAccessContextPerEntity(ac, oew);

    // Confirm result
    // None.
}
 
Example 51
Project: personium-core   File: BoxCacheTest.java   Source Code and License 5 votes vote down vote up
/**
 * Memcachedへの接続に失敗した場合NULLを返すこと.
 * @throws Exception テスト中の例外
 */
@SuppressWarnings("unchecked")
@Test
public void Memcachedへの接続に失敗した場合NULLを返すこと() throws Exception {
    String boxName = "boxCacheTestBox";

    // MemcachedClientのモックを作成(getしたときにMemchachedClientExceptionをthrowするモック)
    Constructor<MemcachedClient> c = MemcachedClient.class.getDeclaredConstructor();
    c.setAccessible(true);
    MemcachedClient mockMemcachedClient = Mockito.spy(c.newInstance());
    Mockito.doThrow(new MemcachedClientException(null)).when(mockMemcachedClient)
            .get(Mockito.anyString(), Mockito.any(Class.class));

    // BoxCacheのモックを作成(MemcachedClientのモックを使用するモック)
    PowerMockito.spy(BoxCache.class);
    PowerMockito.when(BoxCache.class, "getMcdClient").thenReturn(mockMemcachedClient);

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

    // getメソッドのテスト
    CellEsImpl cell = new CellEsImpl();
    cell.setId("CellId");
    Box cache = BoxCache.get(boxName, cell);
    assertNull(cache);
}
 
Example 52
Project: GitHub   File: ProducerSequenceFactoryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testLocalContentUriFullPrefetch() {
  PowerMockito.when(mImageRequest.getSourceUriType())
      .thenReturn(SOURCE_TYPE_LOCAL_CONTENT);
  Producer<Void> producer =
      mProducerSequenceFactory.getDecodedImagePrefetchProducerSequence(mImageRequest);
  assertSame(
      producer,
      mProducerSequenceFactory.mCloseableImagePrefetchSequences.get(
          mProducerSequenceFactory.mLocalContentUriFetchSequence));
}
 
Example 53
Project: qpp-conversion-tool   File: ConversionFileWriterWrapperTest.java   Source Code and License 5 votes vote down vote up
@Test
@PrepareForTest({Files.class, ConversionFileWriterWrapper.class})
public void testFailureToWriteErrors() throws IOException {
	PowerMockito.mockStatic(Files.class);
	PowerMockito.when(Files.newBufferedWriter(ArgumentMatchers.any(Path.class))).thenThrow(new IOException());

	Path path = Paths.get("src/test/resources/not-a-QRDA-III-file.xml");
	ConversionFileWriterWrapper converterWrapper = new ConversionFileWriterWrapper(path);

	converterWrapper.transform();

	assertFileDoesNotExists("not-a-QRDA-III-file.err.json");
}
 
Example 54
Project: Enjin-Coin-Java-SDK   File: NotificationsAsyncServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testInitNotificationsService_GetPlatformAuthResponseVOIsNull() throws Exception {
    GetPlatformAuthResponseVO tempGetPlatformAuthResponseVO = null;
    String auth = "xxxx";
    PlatformServiceImpl mockPlatformService = PowerMockito.mock(PlatformServiceImpl.class);

    PowerMockito.whenNew(PlatformServiceImpl.class).withParameterTypes(Config.class).withArguments(Mockito.isA(Config.class)).thenReturn(mockPlatformService);
    Mockito.when(mockPlatformService.getAuth(Mockito.isA(GetPlatformAuthRequestVO.class))).thenReturn(tempGetPlatformAuthResponseVO);

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

    PowerMockito.verifyNew(PlatformServiceImpl.class).withArguments(Mockito.isA(Config.class));
    Mockito.verify(mockPlatformService, Mockito.times(1)).getAuth(Mockito.isA(GetPlatformAuthRequestVO.class));
}
 
Example 55
Project: Enjin-Coin-Java-SDK   File: NotificationsAsyncServiceTest.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testAddNotificationListener_ListenerAlreadyExists() 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();

    NotificationListenerRegistration addNotificationListenerAsyncRegistration1 = notificationsAsyncService.addNotificationListenerAsync(mockNotificationListener).get();
    assertThat(addNotificationListenerAsyncRegistration1).isNotNull();

    NotificationListenerRegistration addNotificationListenerAsyncRegistration2 = notificationsAsyncService.addNotificationListenerAsync(mockNotificationListener).get();
    assertThat(addNotificationListenerAsyncRegistration2).isNull();

    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));
}
 
Example 56
Project: pac4j-async   File: DefaultAsyncCsrfTokenGeneratorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testCorrectBehaviourWhenNoTokenInSession() throws Exception {

    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(RANDOM_UUID.toString()));
}
 
Example 57
Project: RNLearn_Project1   File: JSDebuggerWebSocketClientTest.java   Source Code and License 5 votes vote down vote up
@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\"}");
}
 
Example 58
Project: stock-api-sdk   File: LicenseTest.java   Source Code and License 5 votes vote down vote up
@Test(groups = "License.downloadAsset", expectedExceptions = {
        StockException.class }, expectedExceptionsMessageRegExp = "Content not licensed but have enough quota or overage plan, so first buy the license")
public void downloadAsset_should_throw_exception_since_asset_not_purchased_but_can_be_licensed() throws Exception{
    String jsonResponse = "{ \"member\": { \"member_id\": \"5PAGXppkUvXRR851OtNbz9HaODSXa7BV\" }, \"available_entitlement\": { \"quota\": 4}, \"contents\": { \"84071201\": { \"content_id\": \"84071201\", \"size\": \"Comp\", \"purchase_details\": { \"state\": \"not_purchased\"} } }, \"purchase_options\": { \"state\": \"not_possible\", \"requires_checkout\": false, \"message\": \"This will use 1 of your 6 licenses.\" } } }";
    
    PowerMockito
    .when(HttpUtils.doGet(Mockito.anyString(),
            Matchers.<Map<String, String>> any()))
    .thenReturn(jsonResponse);
    License api = new License(config);
    api.downloadAsset(new LicenseRequest().setContentId(84071201).setLicenseState(AssetLicenseState.STANDARD), "accessToken");
}
 
Example 59
Project: stock-api-sdk   File: LicenseTest.java   Source Code and License 5 votes vote down vote up
@Test(groups = "License.downloadAsset", expectedExceptions = {
        StockException.class }, expectedExceptionsMessageRegExp = "Content not licensed but have enough quota or overage plan, so first buy the license")
public void downloadAsset_should_throw_exception_since_asset_not_purchased_but_overage_plan_present() throws Exception{
    String jsonResponse = "{ \"member\": { \"member_id\": \"5PAGXppkUvXRR851OtNbz9HaODSXa7BV\" }, \"available_entitlement\": { \"quota\": 0}, \"contents\": { \"84071201\": { \"content_id\": \"84071201\", \"size\": \"Comp\", \"purchase_details\": { \"state\": \"not_purchased\"} } }, \"purchase_options\": { \"state\": \"overage\", \"requires_checkout\": false, \"message\": \"This will use 1 of your 6 licenses.\" } } }";
    
    PowerMockito
    .when(HttpUtils.doGet(Mockito.anyString(),
            Matchers.<Map<String, String>> any()))
    .thenReturn(jsonResponse);
    License api = new License(config);
    api.downloadAsset(new LicenseRequest().setContentId(84071201).setLicenseState(AssetLicenseState.STANDARD), "accessToken");
}
 
Example 60
Project: stock-api-sdk   File: LicenseTest.java   Source Code and License 5 votes vote down vote up
@Test(groups = "License.downloadAsset", expectedExceptions = {
        StockException.class }, expectedExceptionsMessageRegExp = "Could not find the purchase details for the asset")
public void downloadAsset_should_throw_exception_since_asset_url_not_present() throws Exception{
    String jsonResponse = "{ \"member\": { \"member_id\": \"5PAGXppkUvXRR851OtNbz9HaODSXa7BV\" }, \"available_entitlement\": { \"quota\": 4}, \"contents\": { \"84071201\": { \"content_id\": \"84071201\", \"size\": \"Comp\", \"purchase_details\": { \"state\": \"purchased\", \"license\": \"Standard\", \"date\": \"2017-06-21 10:38:52\", \"content_type\": \"image/jpeg\", \"width\": 4000, \"height\": 3928 } } } } }";
    
    PowerMockito
    .when(HttpUtils.doGet(Mockito.anyString(),
            Matchers.<Map<String, String>> any()))
    .thenReturn(jsonResponse);
    License api = new License(config);
    api.downloadAsset(new LicenseRequest().setContentId(84071201).setLicenseState(AssetLicenseState.STANDARD), "accessToken");
}