Java Code Examples for org.powermock.api.mockito.PowerMockito#mock()

The following examples show how to use org.powermock.api.mockito.PowerMockito#mock() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GDXFacebookLoaderUnitTests.java    From gdx-facebook with Apache License 2.0 6 votes vote down vote up
@Test
public void returnHTMLGDXFacebookWhenOnWebGL() {
    Application mockApplication = mock(Application.class);
    when(mockApplication.getType()).thenReturn(Application.ApplicationType.WebGL);
    Gdx.app = mockApplication;

    try {
        Constructor mockConstructor = PowerMockito.mock(Constructor.class);
        GDXFacebook mockFacebook = mock(HTMLGDXFacebook.class);

        when(ClassReflection.forName(GDXFacebookVars.CLASSNAME_HTML)).thenReturn(HTMLGDXFacebook.class);
        when(ClassReflection.getConstructor(HTMLGDXFacebook.class, GDXFacebookConfig.class)).thenReturn(mockConstructor);
        when(mockConstructor.newInstance(anyObject())).thenReturn(mockFacebook);

    } catch (ReflectionException e) {
        e.printStackTrace();
    }

    facebook = GDXFacebookSystem.install(new GDXFacebookConfig());
    assertTrue(facebook instanceof HTMLGDXFacebook);
}
 
Example 2
Source File: TestJvmUtils.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void findMainClass_jar_null() throws Exception {
  String content = "Manifest-Version: 1.0\n";
  InputStream inputStream = new ByteArrayInputStream(content.getBytes());

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

  String command = "a.jar";
  String manifestUri = "jar:file:/" + new File(command).getAbsolutePath() + "!/" + JarFile.MANIFEST_NAME;

  PowerMockito.whenNew(URL.class).withParameterTypes(String.class)
      .withArguments(manifestUri).thenReturn(url);
  PowerMockito.when(url.openStream()).thenReturn(inputStream);

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

  Assert.assertNull(JvmUtils.findMainClass());
}
 
Example 3
Source File: GoogleAuthProviderTest.java    From gdx-fireapp with Apache License 2.0 6 votes vote down vote up
@Override
public void setup() {
    super.setup();
    PowerMockito.mockStatic(GIDSignIn.class);
    PowerMockito.mockStatic(UITableViewController.class);
    PowerMockito.mockStatic(GIDSignInUIDelegate.class);
    PowerMockito.mockStatic(GIDSignInDelegate.class);
    PowerMockito.mockStatic(GoogleAuthProvider.GIDViewController.class);
    PowerMockito.mockStatic(GoogleAuthProvider.GIDSignDelegate.class);
    PowerMockito.mockStatic(FIRApp.class);
    PowerMockito.mockStatic(FIROptions.class);
    gidSignIn = PowerMockito.mock(GIDSignIn.class);
    Mockito.when(GIDSignIn.sharedInstance()).thenReturn(gidSignIn);
    FIRApp firApp = PowerMockito.mock(FIRApp.class);
    Mockito.when(firApp.options()).thenReturn(PowerMockito.mock(FIROptions.class));
    Mockito.when(FIRApp.defaultApp()).thenReturn(firApp);
    Mockito.when(GoogleAuthProvider.GIDViewController.alloc()).thenReturn(PowerMockito.mock(GoogleAuthProvider.GIDViewController.class));
}
 
Example 4
Source File: DaoSqlBriteIntegrationTest.java    From sqlbrite-dao with Apache License 2.0 6 votes vote down vote up
@Test public void runRawStatementQueryWithTables() {
  BriteDatabase db = PowerMockito.mock(BriteDatabase.class);
  userDao.setSqlBriteDb(db);

  String arg1 = "arg1", arg2 = "arg2";
  String table = "Table";
  String sql = "SELECT * FROM " + table;
  List<String> argsList = Arrays.asList(arg1, arg2);
  Set<String> tables = Collections.singleton(table);

  userDao.rawQueryOnManyTables(tables, sql).args(arg1, arg2).run();

  ArgumentCaptor<String> varArgs = ArgumentCaptor.forClass(String.class);

  QueryObservable query = Mockito.verify(db, Mockito.times(1))
      .createQuery(Mockito.eq(tables), Mockito.eq(sql), varArgs.capture());

  Assert.assertEquals(argsList, varArgs.getAllValues());
}
 
Example 5
Source File: DefaultAuthenticationRequestHandlerTest.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Test(expectedExceptions = PostAuthenticationFailedException.class)
public void testPostAuthenticationHandlerFailures() throws Exception {

    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = PowerMockito.mock(HttpServletRequest.class);
    HttpServletResponse response = PowerMockito.mock(HttpServletResponse.class);
    AuthenticationContext context = prepareContextForPostAuthnTests();
    when(FrameworkUtils.getStepBasedSequenceHandler()).thenReturn(new DefaultStepBasedSequenceHandler());
    authenticationRequestHandler.handle(request, response, context);
    assertNull(context.getParameter(FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED));
    String pastrCookie = context.getParameter(FrameworkConstants.PASTR_COOKIE).toString();
    cookies[0] = new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(), pastrCookie);
    when(request.getCookies()).thenReturn(cookies);
    when(FrameworkUtils.getCookie(any(HttpServletRequest.class), anyString())).thenReturn
            (new Cookie(FrameworkConstants.PASTR_COOKIE + "-" + context.getContextIdentifier(),
                    "someGibberishValue"));
    authenticationRequestHandler.handle(request, response, context);
    assertTrue(Boolean.parseBoolean(context.getProperty(
            FrameworkConstants.POST_AUTHENTICATION_EXTENSION_COMPLETED).toString()));
}
 
Example 6
Source File: MarathonBuilderImplFileTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testReadDirectoryFile() throws InterruptedException, MarathonFileMissingException, MarathonFileInvalidException, IOException {
    final String   filename = "somefile";
    final FilePath wsMock   = PowerMockito.mock(FilePath.class);
    final FilePath fileMock = PowerMockito.mock(FilePath.class);
    when(wsMock.child(anyString())).thenReturn(fileMock);
    when(fileMock.exists()).thenReturn(true);
    when(fileMock.isDirectory()).thenReturn(true);

    // create builder
    builder = new MarathonBuilderImpl(appConfig);

    // setup FileInvalid exception
    exception.expect(MarathonFileInvalidException.class);
    builder.setWorkspace(wsMock).read(filename);
}
 
Example 7
Source File: ProducerOperationHandlerInterceptorTest.java    From skywalking with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws Exception {
    ServiceManager.INSTANCE.boot();
    invocationInterceptor = new ProducerOperationHandlerInterceptor();
    PowerMockito.mock(Invocation.class);
    when(operationMeta.getSchemaMeta()).thenReturn(schemaMeta);
    when(endpoint.getAddress()).thenReturn("0.0.0.0:7777");
    when(invocation.getEndpoint()).thenReturn(endpoint);
    when(invocation.getMicroserviceQualifiedName()).thenReturn("productorTest");
    when(operationMeta.getOperationPath()).thenReturn("/bmi");
    when(invocation.getOperationMeta()).thenReturn(operationMeta);
    when(invocation.getStatus()).thenReturn(statusType);
    when(statusType.getStatusCode()).thenReturn(200);
    when(method.getName()).thenReturn("producer");
    when(invocation.getInvocationType()).thenReturn(InvocationType.PRODUCER);
    Config.Agent.SERVICE_NAME = "serviceComnTestCases-APP";

    allArguments = new Object[] {invocation};
    argumentsType = new Class[] {};
    swaggerArguments = new Class[] {};

}
 
Example 8
Source File: AbbyyResponseParserTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
private AbbyyResponse.Builder mockAbbyyResponseBuilder() {
    AbbyyResponse.Builder abbyyResponseBuilderMock = PowerMockito.mock(AbbyyResponse.Builder.class);
    when(abbyyResponseBuilderMock.taskId(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.credits(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.taskStatus(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.errorMessage(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.resultUrl(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.resultUrl2(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.resultUrl3(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.estimatedProcessingTime(anyString())).thenReturn(abbyyResponseBuilderMock);
    when(abbyyResponseBuilderMock.build()).thenReturn(mock(AbbyyResponse.class));
    return abbyyResponseBuilderMock;
}
 
Example 9
Source File: InventoryUtilTest.java    From pacbot with Apache License 2.0 5 votes vote down vote up
/**
 * Fetch dynamo DB tables test.
 *
 * @throws Exception the exception
 */
@SuppressWarnings("static-access")
@Test
public void fetchDynamoDBTablesTest() throws Exception {
    
    mockStatic(AmazonDynamoDBClientBuilder.class);
    AmazonDynamoDB awsClient = PowerMockito.mock(AmazonDynamoDB.class);
    AmazonDynamoDBClientBuilder amazonDynamoDBClientBuilder = PowerMockito.mock(AmazonDynamoDBClientBuilder.class);
    AWSStaticCredentialsProvider awsStaticCredentialsProvider = PowerMockito.mock(AWSStaticCredentialsProvider.class);
    PowerMockito.whenNew(AWSStaticCredentialsProvider.class).withAnyArguments().thenReturn(awsStaticCredentialsProvider);
    when(amazonDynamoDBClientBuilder.standard()).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.withCredentials(anyObject())).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.withRegion(anyString())).thenReturn(amazonDynamoDBClientBuilder);
    when(amazonDynamoDBClientBuilder.build()).thenReturn(awsClient);
    
    ListTablesResult listTableResult = new ListTablesResult();
    List<String> tables = new ArrayList<>();
    tables.add(new String());
    listTableResult.setTableNames(tables);
    when(awsClient.listTables()).thenReturn(listTableResult);
    
    DescribeTableResult describeTableResult = new DescribeTableResult();
    TableDescription table = new TableDescription();
    table.setTableArn("tableArn");
    describeTableResult.setTable(table);
    when(awsClient.describeTable(anyString())).thenReturn(describeTableResult);
    
    when(awsClient.listTagsOfResource(anyObject())).thenReturn(new ListTagsOfResourceResult());
    assertThat(inventoryUtil.fetchDynamoDBTables(new BasicSessionCredentials("awsAccessKey", "awsSecretKey", "sessionToken"), 
            "skipRegions", "account","accountName").size(), is(1));
    
}
 
Example 10
Source File: TenantLoadMessageSenderTest.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test(expected = ClusteringFault.class)
public void testSendTenantRegistryLoadMessageFail() throws ClusteringFault {
    ClusteringAgent clusteringAgent = PowerMockito.mock(ClusteringAgent.class);
    ClusteringCommand command = PowerMockito.mock(ClusteringCommand.class);
    List<ClusteringCommand> commandList = new ArrayList<ClusteringCommand>();
    commandList.add(command);
    ClusteringFault clusteringFault = PowerMockito.mock(ClusteringFault.class);
    PowerMockito.when(clusteringAgent.sendMessage(Matchers.any(TenantLoadMessage.class), Matchers.anyBoolean())).
            thenThrow(clusteringFault);
    tenantLoadMessageSender.sendTenantLoadMessage(clusteringAgent, 1, "a.com", 2);
}
 
Example 11
Source File: DataProcessorTest.java    From gdx-fireapp with Apache License 2.0 5 votes vote down vote up
@Test
public void processPrimitiveData_boolean() {
    // Given
    NSNumber iosObject = PowerMockito.mock(NSNumber.class);

    // When
    Object result = DataProcessor.processPrimitiveData(iosObject, Boolean.class);

    // Then
    Assert.assertTrue(result instanceof Boolean);
}
 
Example 12
Source File: HttpClientTest.java    From cs-actions with Apache License 2.0 5 votes vote down vote up
@Test
public void execute_httpRequestFails_HttpException() throws Exception {
    //Arrange
    final String returnResult = "return result";
    final String exception = "exception";
    final String statusCode = "status code";
    final String responseHeaders = "response headers";
    final String returnCode = ReturnCodes.FAILURE;

    Map<String, String> rawResponse = new HashMap<>();
    rawResponse.put(HttpClientOutputNames.RETURN_RESULT, returnResult);
    rawResponse.put(HttpClientOutputNames.EXCEPTION, exception);
    rawResponse.put(HttpClientOutputNames.STATUS_CODE, statusCode);
    rawResponse.put(HttpClientOutputNames.RESPONSE_HEADERS, responseHeaders);
    rawResponse.put(HttpClientOutputNames.RETURN_CODE, returnCode);
    HttpClientAction httpClientActionMock = PowerMockito.mock(HttpClientAction.class);
    PowerMockito.whenNew(HttpClientAction.class).withAnyArguments().thenReturn(httpClientActionMock);
    when(httpClientActionMock.execute(anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(), anyString(),
            any(SerializableSessionObject.class), any(GlobalSessionObject.class))).thenReturn(rawResponse);

    HttpClientResponse.Builder httpClientResponseBuilderSpy = new HttpClientResponse.Builder();
    httpClientResponseBuilderSpy = PowerMockito.spy(httpClientResponseBuilderSpy);
    when(httpClientResponseBuilderSpy.build()).thenReturn(null);
    PowerMockito.whenNew(HttpClientResponse.Builder.class).withAnyArguments().thenReturn(httpClientResponseBuilderSpy);

    //Assert
    this.exception.expect(HttpClientException.class);

    //Act
    HttpClient.execute(httpRequestMock);
}
 
Example 13
Source File: WXImageTest.java    From weex-uikit with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {

  mInstance = WXSDKInstanceTest.createInstance();
  mDomObject = new TestDomObject();
  PowerMockito.when(Mockito.spy(mDomObject).clone()).thenReturn(mDomObject);
  mWXDiv = PowerMockito.mock(WXDiv.class);
  mWXImage = new WXImage(mInstance, mDomObject, mWXDiv);

}
 
Example 14
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example 15
Source File: FileReaderWriterFactoryTest.java    From secor with Apache License 2.0 5 votes vote down vote up
private void mockDelimitedTextFileWriter(boolean isCompressed) throws Exception {
    PowerMockito.mockStatic(FileSystem.class);
    FileSystem fs = Mockito.mock(FileSystem.class);
    Mockito.when(
            FileSystem.get(Mockito.any(URI.class),
                    Mockito.any(Configuration.class))).thenReturn(fs);

    Path fsPath = (!isCompressed) ? new Path(PATH) : new Path(PATH_GZ);

    GzipCodec codec = PowerMockito.mock(GzipCodec.class);
    PowerMockito.whenNew(GzipCodec.class).withNoArguments()
            .thenReturn(codec);

    FSDataInputStream fileInputStream = Mockito
            .mock(FSDataInputStream.class);
    FSDataOutputStream fileOutputStream = Mockito
            .mock(FSDataOutputStream.class);

    Mockito.when(fs.open(fsPath)).thenReturn(fileInputStream);
    Mockito.when(fs.create(fsPath)).thenReturn(fileOutputStream);

    CompressionInputStream inputStream = Mockito
            .mock(CompressionInputStream.class);
    CompressionOutputStream outputStream = Mockito
            .mock(CompressionOutputStream.class);
    Mockito.when(codec.createInputStream(Mockito.any(InputStream.class)))
            .thenReturn(inputStream);

    Mockito.when(codec.createOutputStream(Mockito.any(OutputStream.class)))
            .thenReturn(outputStream);
}
 
Example 16
Source File: UnderlabelValidatorTest.java    From AwesomeValidation with MIT License 5 votes vote down vote up
public void testValidationCallbackExecute() throws Exception {
    ValidationCallback validationCallback = Whitebox.getInternalState(mSpiedUnderlabelValidator, "mValidationCallback");
    Whitebox.setInternalState(mSpiedUnderlabelValidator, "mHasFailed", false);
    TextView mockTextView = mock(TextView.class);
    Matcher mockMatcher = PowerMockito.mock(Matcher.class);
    Drawable mockDrawable = mock(Drawable.class);
    when(mMockValidationHolder.getEditText().getBackground()).thenReturn(mockDrawable);
    doNothing().when(mockDrawable).setColorFilter(anyInt(), any(PorterDuff.Mode.class));
    PowerMockito.doReturn(mockTextView).when(mSpiedUnderlabelValidator, "replaceView", mMockValidationHolder);
    validationCallback.execute(mMockValidationHolder, mockMatcher);
}
 
Example 17
Source File: ReactNativeUtilTest.java    From react-native-azurenotificationhub with MIT License 5 votes vote down vote up
@Test
public void testGetSoundUriDefault() {
    final String soundName = "default";

    Uri expectedSoundUri = PowerMockito.mock(Uri.class);
    when(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)).thenReturn(expectedSoundUri);
    when(mBundle.getString(KEY_REMOTE_NOTIFICATION_SOUND_NAME)).thenReturn(soundName);

    Uri soundUri = getSoundUri(mReactApplicationContext, mBundle);

    Assert.assertEquals(soundUri, expectedSoundUri);
    verifyStatic(Uri.class, times(0));
    Uri.parse(anyString());
}
 
Example 18
Source File: EmailTemplateDaoImplTest.java    From sunbird-lms-service with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  emailTemplateDao = new EmailTemplateDaoImpl();
  cassandraOperation = PowerMockito.mock(CassandraOperation.class);
  PowerMockito.mockStatic(ServiceFactory.class);
  when(ServiceFactory.getInstance()).thenReturn(cassandraOperation);
}
 
Example 19
Source File: OvsdbManagersRemovedCommandTest.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
@Before
public void setUp() {
    ovsdbManagersRemovedCommand = PowerMockito.mock(OvsdbManagersRemovedCommand.class, Mockito.CALLS_REAL_METHODS);
}
 
Example 20
Source File: VpcFlowLogsEnabledTest.java    From pacbot with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception{
    ec2Client = PowerMockito.mock(AmazonEC2.class); 
}