Java Code Examples for org.mockito.Mockito#spy()

The following examples show how to use org.mockito.Mockito#spy() . These examples are extracted from open source projects. 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 Project: cia   File: SendEmailClickListenerTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Show notification failure test.
 */
@Test
public void showNotificationFailureTest() {
	final SendEmailRequest request = new SendEmailRequest();		
	final SendEmailClickListener listener = Mockito.spy(new SendEmailClickListener(request));
	final ApplicationManager applicationManager = Mockito.mock(ApplicationManager.class);
	Mockito.doReturn(applicationManager).when(listener).getApplicationManager();
	
	final SendEmailResponse sendEmailResponse = new SendEmailResponse(ServiceResult.FAILURE);
	sendEmailResponse.setErrorMessage("errorMessage");
	Mockito.when(applicationManager.service(request)).thenReturn(sendEmailResponse);
	
	Mockito.doNothing().when(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
	listener.buttonClick(new ClickEvent(new Panel()));
	Mockito.verify(listener).showNotification(ArgumentMatchers.anyString(), ArgumentMatchers.anyString(), ArgumentMatchers.any(Type.class));
}
 
Example 2
protected void doRequest() throws MalformedURLException, IOException, HttpException {
    JavaHttpProvider javaHttpProvider = (JavaHttpProvider) JavaHttpProvider.builder().build();
    JavaHttpProvider mock = Mockito.spy(javaHttpProvider);
    mockHttpUrlConnection = getMockHttpUrlConnection();
    Mockito.doReturn(mockHttpUrlConnection).when(mock).getHttpUrlConnection(Mockito.anyString());

    HttpProvider.HttpRequest httpRequest;
    if (callGetRequest) {
        httpRequest = mock.getRequest(httpRequestAuthorizer, method, urlString, jsonBody);
    } else {
        if (null != jsonBody) {
            httpRequest = javaHttpProvider.getRequest(httpRequestAuthorizer, method, urlString, jsonBody);
        } else {
            httpRequest = javaHttpProvider.getRequest(httpRequestAuthorizer, method, urlString, formParams);
        }
    }
    if (addAdditionalHeaders) {
        httpRequest.addHeader(additionalHeaderName, additionalHeaderValue);
    }

    HttpResponse httpResponse = mock.execute(httpRequest);
    assertTrue("httpResponse was null", null != httpResponse);
}
 
Example 3
Source Project: blueocean-plugin   File: FreeStylePipelineTest.java    License: MIT License 6 votes vote down vote up
@Test
public void findModernRun() throws Exception {
    FreeStyleProject freestyle = Mockito.spy(j.createProject(FreeStyleProject.class, "freestyle"));

    FreeStyleBuild build1 = Mockito.mock(FreeStyleBuild.class);
    FreeStyleBuild build2 = Mockito.mock(FreeStyleBuild.class);

    Mockito.when(build1.getParent()).thenReturn(freestyle);
    Mockito.when(build1.getNextBuild()).thenReturn(build2);

    Mockito.when(build2.getParent()).thenReturn(freestyle);
    Mockito.when(build2.getPreviousBuild()).thenReturn(build1);

    RunList<FreeStyleBuild> runs = RunList.fromRuns(Arrays.asList(build1, build2));
    Mockito.doReturn(runs).when(freestyle).getBuilds();
    Mockito.doReturn(build2).when(freestyle).getLastBuild();

    FreeStylePipeline freeStylePipeline = (FreeStylePipeline) BluePipelineFactory.resolve(freestyle);
    assertNotNull(freeStylePipeline);
    BlueRun blueRun = freeStylePipeline.getLatestRun();
    assertNotNull(blueRun);
    Links links = blueRun.getLinks();
    assertNotNull(links);
    assertNotNull(links.get("self"));
}
 
Example 4
Source Project: gdx-fireapp   File: DatabaseTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void readValue() throws Exception {
        // Given
        PowerMockito.mockStatic(QueryReadValue.class);
        Database database = new Database();
        QueryReadValue query = Mockito.spy(new QueryReadValue(database, "/test"));
        PowerMockito.whenNew(QueryReadValue.class).withAnyArguments().thenReturn(query);

        // When
        database.inReference("/test").readValue(String.class).subscribe();

        // Then
//        verify(mapConverter, VerificationModeFactory.times(1)).convert(any(Map.class), any(Class.class));
        PowerMockito.verifyNew(QueryReadValue.class);
        // TODO - verify converter
    }
 
Example 5
Source Project: joal   File: TrackerClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldRemoveOneFromSeeders() throws AnnounceException {
    // should remove one seeder because we are one of them
    final TrackerClientUriProvider uriProvider = Mockito.spy(TrackerClientUriProviderTest.createOne("https://localhost"));

    final TrackerClient trackerClient = Mockito.spy(new TrackerClient(uriProvider, mock(TrackerResponseHandler.class), Mockito.mock(HttpClient.class)));
    Mockito.doReturn(
            this.createMockedTrackerSuccessMessage()
    ).when(trackerClient).makeCallAndGetResponseAsByteBuffer(any(URI.class), anyString(), any());

    final SuccessAnnounceResponse announceResponse = trackerClient.announce("param=val&dd=q", this.createHeaders());

    final HTTPAnnounceResponseMessage expected = this.createMockedTrackerSuccessMessage();
    assertThat(announceResponse.getLeechers()).isEqualTo(expected.getIncomplete());
    assertThat(announceResponse.getSeeders()).isEqualTo(expected.getComplete() - 1);
    assertThat(announceResponse.getInterval()).isEqualTo(expected.getInterval());
}
 
Example 6
Source Project: aws-mock   File: MockEC2QueryHandlerTest.java    License: MIT License 6 votes vote down vote up
@Test
public void Test_describeVolumes() throws Exception {
	MockEC2QueryHandler handler = MockEC2QueryHandler.getInstance();
	MockVolumeController controller = Mockito.spy(MockVolumeController.class);
    Whitebox.setInternalState(handler, "mockVolumeController", controller);

    CreateVolumeResponseType retCreate = Whitebox.invokeMethod(handler, "createVolume", "VolumeType", "23GB", "us-east-1a", 23, "2323");

    Assert.assertTrue(retCreate != null);
    Assert.assertTrue(retCreate.getVolumeId() != null);
    DescribeVolumesResponseType volumeResponseType = Whitebox.invokeMethod(handler, "describeVolumes", "", 50);

    Assert.assertTrue(volumeResponseType != null);
    Assert.assertTrue(volumeResponseType.getVolumeSet().getItem().size() == 1); // has one VPC

    Assert.assertTrue(volumeResponseType.getVolumeSet().getItem().get(0).getVolumeType() != null);
    
    DeleteVolumeResponseType deleteVolumeResponseType = Whitebox.invokeMethod(handler, "deleteVolume", volumeResponseType.getVolumeSet().getItem().get(0).getVolumeId());
    Assert.assertTrue(deleteVolumeResponseType != null);
}
 
Example 7
/**
 * translog読み込み時にFlushNotAllowedEngineExceptionが発生した場合にflushが実行されること.
 * @throws Exception 実行時例外
 */
@Test
public void translogのflush時にFlushNotAllowedEngineExceptionが発生した場合にflushのリトライをしないこと()
        throws Exception {

    Constructor<FlushTranslogRetryableRequest> constructor = FlushTranslogRetryableRequest.class
            .getDeclaredConstructor(new Class[] {EsTranslogHandler.class, Integer.TYPE, Long.TYPE });
    constructor.setAccessible(true);
    EsTranslogHandler handler = new EsTranslogHandler(RETRY_COUNT, 0, null, INDEX_FOR_TEST);
    FlushTranslogRetryableRequest flushMock = Mockito.spy((FlushTranslogRetryableRequest) constructor.newInstance(
            handler, 5, 0L));

    FlushNotAllowedEngineException toBeThrown = Mockito.mock(FlushNotAllowedEngineException.class);
    Mockito.doThrow(toBeThrown) // 初回リクエストの例外投入
            .doReturn(null)
            .when(flushMock)
            .doProcess();

    flushMock.doRequest();
    Mockito.verify(flushMock, Mockito.times(1)).doProcess(); // ParticularErrorのためリトライしないこと
    Mockito.verify(flushMock, Mockito.times(0)).flushTransLog();
}
 
Example 8
Source Project: joal   File: TrackerClientTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void shouldNotFailToRemoveOneFromSeedersIfThereIsNoSeeders() throws AnnounceException {
    // should remove one seeder because we are one of them
    final TrackerClientUriProvider uriProvider = Mockito.spy(TrackerClientUriProviderTest.createOne("https://localhost"));

    final TrackerClient trackerClient = Mockito.spy(new TrackerClient(uriProvider, mock(TrackerResponseHandler.class), Mockito.mock(HttpClient.class)));
    Mockito.doReturn(
            this.createMockedTrackerSuccessMessage(0)
    ).when(trackerClient).makeCallAndGetResponseAsByteBuffer(any(URI.class), anyString(), any());

    final SuccessAnnounceResponse announceResponse = trackerClient.announce("param=val&dd=q", this.createHeaders());

    final HTTPAnnounceResponseMessage expected = this.createMockedTrackerSuccessMessage();
    assertThat(announceResponse.getLeechers()).isEqualTo(expected.getIncomplete());
    assertThat(announceResponse.getSeeders()).isEqualTo(0);
    assertThat(announceResponse.getInterval()).isEqualTo(expected.getInterval());
}
 
Example 9
Source Project: aws-mock   File: MockEc2ControllerTest.java    License: MIT License 5 votes vote down vote up
@Test(expected = BadEc2RequestException.class)
public void Test_runInstancesMinCountGreaterThanMaxCount() throws Exception {

    MockEc2Controller controller = Mockito.spy(MockEc2Controller.class);
    controller.runInstances(DefaultMockEc2Instance.class, "ImageName",
            InstanceType.C1_MEDIUM.getName(), 11, 10);
}
 
Example 10
Source Project: crnk-framework   File: BasicActionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void setupFeature(CrnkTestFeature feature) {
	filter = Mockito.spy(new DocumentFilter() {

		@Override
		public Response filter(DocumentFilterContext filterRequestContext, DocumentFilterChain chain) {
			return chain.doFilter(filterRequestContext);
		}
	});
	SimpleModule testModule = new SimpleModule("testFilter");
	testModule.addFilter(filter);
	feature.addModule(testModule);
}
 
Example 11
Source Project: hadoop   File: TestChRootedFs.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testIsValidNameInvalidInBaseFs() throws Exception {
  AbstractFileSystem baseFs = Mockito.spy(fc.getDefaultFileSystem());
  ChRootedFs chRootedFs = new ChRootedFs(baseFs, new Path("/chroot"));
  Mockito.doReturn(false).when(baseFs).isValidName(Mockito.anyString());
  Assert.assertFalse(chRootedFs.isValidName("/test"));
  Mockito.verify(baseFs).isValidName("/chroot/test");
}
 
Example 12
Source Project: besu   File: AbstractNatManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void assertThatDoStartIsCalledOnlyOnce() throws NatInitializationException {
  final AbstractNatManager natManager = Mockito.spy(buildNatManager(NatMethod.UPNP));
  natManager.start();
  natManager.start();
  verify(natManager, times(2)).start();
  verify(natManager).doStart();
}
 
Example 13
@Test
public void testCustomConfigs() throws Exception {
  RemoteSSOService service = Mockito.spy(new RemoteSSOService());

  Configuration conf = new Configuration();
  conf.set(RemoteSSOService.DPM_BASE_URL_CONFIG, "http://foo");
  conf.set(RemoteSSOService.SECURITY_SERVICE_APP_AUTH_TOKEN_CONFIG, "authToken");
  conf.set(RemoteSSOService.SECURITY_SERVICE_COMPONENT_ID_CONFIG, "serviceComponentId");
  conf.set(RemoteSSOService.SECURITY_SERVICE_VALIDATE_AUTH_TOKEN_FREQ_CONFIG, 30);
  conf.set(RemoteSSOService.SECURITY_SERVICE_CONNECTION_TIMEOUT_CONFIG, 2000);
  service.setConfiguration(conf);
  Assert.assertEquals("http://foo/security/login", service.getLoginPageUrl());
  Assert.assertEquals("http://foo/security/_logout", service.getLogoutUrl());
  Assert.assertEquals(2000, service.getConnectionTimeout());
}
 
Example 14
Source Project: joal   File: ConnectionHandlerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void shouldFillPortAndIpOnInit() throws IOException {
    final ServerSocketChannel channel = createMockedServerSocketChannel(65534);
    final ConnectionHandler handler = Mockito.spy(new ConnectionHandler());
    doReturn(channel).when(handler).bindToPort();
    doReturn(Optional.of(InetAddress.getByName("168.168.168.168"))).when(handler).tryToFetchFromProviders();

    handler.start();

    assertThat(handler.getIpAddress().getHostAddress()).isEqualTo("168.168.168.168");
    assertThat(handler.getPort()).isEqualTo(65534);
}
 
Example 15
Source Project: datacollector   File: TestStatsInfo.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRollIfNeededRollFrequencyPassed() {
  BuildInfo buildInfo = Mockito.mock(BuildInfo.class);
  Mockito.when(buildInfo.getVersion()).thenReturn("v1");
  Mockito.when(buildInfo.getBuiltRepoSha()).thenReturn("sha1");
  RuntimeInfo runtimeInfo = mockRuntimeInfo("id", false);

  StatsInfo si = createStatsInfo();
  si = Mockito.spy(si);
  Mockito.doReturn(ImmutableMap.of("a", "A")).when(si).getExtraInfo(sysInfo);

  TestModelStatsExtension ext = getTestExtension(si);

  si.getActiveStats().setSdcId("id");
  si.getActiveStats().setProductName(RuntimeInfo.SDC_PRODUCT);
  si.getActiveStats().setDataCollectorVersion("v1");
  si.getActiveStats().setBuildRepoSha("sha1");
  si.getActiveStats().setExtraInfo(ImmutableMap.of("a", "A"));
  si.getActiveStats().setStartTime(System.currentTimeMillis() - 2);
  si.getActiveStats().setDpmEnabled(false);

  Assert.assertTrue(si.rollIfNeeded(buildInfo, runtimeInfo, sysInfo, 1, false, System.currentTimeMillis()));
  Mockito.verify(si, Mockito.times(1)).doWithLock(Mockito.any(Runnable.class), Mockito.eq(true));
  Assert.assertEquals(1, ext.getRolls());

  Assert.assertEquals("v1", si.getActiveStats().getDataCollectorVersion());
  Assert.assertEquals(1, si.getCollectedStats().size());
}
 
Example 16
@Test
public void configTest() {
  Map<String, String> options = new HashMap<>();
  String serviceName = "myGreatService";
  String endpoint = "http://127.0.0.1:9090";
  options.put("otel.zipkin.service.name", serviceName);
  options.put("otel.zipkin.endpoint", endpoint);
  ZipkinSpanExporter.Builder config = ZipkinSpanExporter.newBuilder();
  ZipkinSpanExporter.Builder spy = Mockito.spy(config);
  spy.fromConfigMap(options, ConfigBuilderTest.getNaming()).build();
  Mockito.verify(spy).setServiceName(serviceName);
  Mockito.verify(spy).setEndpoint(endpoint);
}
 
Example 17
Source Project: cloudstack   File: VmwareContextTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUploadResourceContentCharsetException() throws Exception {
    VmwareClient client = Mockito.mock(VmwareClient.class);
    String address = "10.1.1.1";
    VmwareContext vmwareContext = Mockito.spy(new VmwareContext(client, address));
    HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
    Mockito.doReturn(Mockito.mock(OutputStream.class)).when(conn).getOutputStream();
    Mockito.doReturn(Mockito.mock(InputStream.class)).when(conn).getInputStream();
    Mockito.doReturn(conn).when(vmwareContext).getHTTPConnection("http://example.com", "PUT");
    //This method should not throw any exception. Ref: CLOUDSTACK-8669
    vmwareContext.uploadResourceContent("http://example.com", "content".getBytes());
}
 
Example 18
@Test
public void testAuthenticate() throws Exception {
    SAML2LoginAPIAuthenticatorCmd cmd = Mockito.spy(new SAML2LoginAPIAuthenticatorCmd());

    Field apiServerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("apiServer");
    apiServerField.setAccessible(true);
    apiServerField.set(cmd, apiServer);

    Field managerField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("samlAuthManager");
    managerField.setAccessible(true);
    managerField.set(cmd, samlAuthManager);

    Field accountServiceField = BaseCmd.class.getDeclaredField("_accountService");
    accountServiceField.setAccessible(true);
    accountServiceField.set(cmd, accountService);

    Field domainMgrField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("domainMgr");
    domainMgrField.setAccessible(true);
    domainMgrField.set(cmd, domainMgr);

    Field userAccountDaoField = SAML2LoginAPIAuthenticatorCmd.class.getDeclaredField("userAccountDao");
    userAccountDaoField.setAccessible(true);
    userAccountDaoField.set(cmd, userAccountDao);

    KeyPair kp = CertUtils.generateRandomKeyPair(4096);
    X509Certificate cert = SAMLUtils.generateRandomX509Certificate(kp);

    SAMLProviderMetadata providerMetadata = new SAMLProviderMetadata();
    providerMetadata.setEntityId("random");
    providerMetadata.setSigningCertificate(cert);
    providerMetadata.setEncryptionCertificate(cert);
    providerMetadata.setKeyPair(kp);
    providerMetadata.setSsoUrl("http://test.local");
    providerMetadata.setSloUrl("http://test.local");

    Mockito.lenient().when(session.getAttribute(Mockito.anyString())).thenReturn(null);

    Mockito.lenient().when(domain.getId()).thenReturn(1L);
    Mockito.lenient().when(domainMgr.getDomain(Mockito.anyString())).thenReturn(domain);
    UserAccountVO user = new UserAccountVO();
    user.setId(1000L);
    Mockito.lenient().when(userAccountDao.getUserAccount(Mockito.anyString(), Mockito.anyLong())).thenReturn(user);
    Mockito.lenient().when(apiServer.verifyUser(nullable(Long.class))).thenReturn(false);
    Mockito.when(samlAuthManager.getSPMetadata()).thenReturn(providerMetadata);
    Mockito.when(samlAuthManager.getIdPMetadata(nullable(String.class))).thenReturn(providerMetadata);

    Map<String, Object[]> params = new HashMap<String, Object[]>();

    // SSO redirection test
    cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    Mockito.verify(resp, Mockito.times(1)).sendRedirect(Mockito.anyString());

    // SSO SAMLResponse verification test, this should throw ServerApiException for auth failure
    params.put(SAMLPluginConstants.SAML_RESPONSE, new String[]{"Some String"});
    Mockito.when(cmd.processSAMLResponse(Mockito.anyString())).thenReturn(buildMockResponse());
    boolean failing = true;
    try {
        cmd.authenticate("command", params, session, InetAddress.getByName("127.0.0.1"), HttpUtils.RESPONSE_TYPE_JSON, new StringBuilder(), req, resp);
    } catch (ServerApiException ignored) {
        failing = false;
    }
    assertFalse("authentication should not have succeeded", failing);
    Mockito.verify(userAccountDao, Mockito.times(0)).getUserAccount(Mockito.anyString(), Mockito.anyLong());
    Mockito.verify(apiServer, Mockito.times(0)).verifyUser(Mockito.anyLong());
}
 
Example 19
Source Project: botsing   File: GuidedMutationTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testMutation() throws NoSuchMethodException, ConstructionFailedException, ClassNotFoundException, FileNotFoundException {
    TestCase testCase = getIntTest(20);
    TestChromosome chromosome = new TestChromosome();
    chromosome.setTestCase(testCase);
    // Mock target inst
    BytecodeInstruction instruction = Mockito.mock(BytecodeInstruction.class);
    Mockito.doReturn("java.lang.Integer").when(instruction).getClassName();
    Mockito.doReturn("reverse()").when(instruction).getMethodName();
    Mockito.doReturn(1).when(instruction).getLineNumber();
    ActualControlFlowGraph acfg = Mockito.mock(ActualControlFlowGraph.class);
    Mockito.doReturn(Opcodes.ACC_PUBLIC).when(acfg).getMethodAccess();
    Mockito.doReturn(acfg).when(instruction).getActualCFG();

    // Add taget inst
    BytecodeInstructionPool.getInstance(TestGenerationContext.getInstance().getClassLoaderForSUT()).registerInstruction(instruction);
    Properties.TARGET_CLASS = "java.lang.Integer";

    // Mock the given stack trace
    BufferedReader givenStackTrace = new BufferedReader(new StringReader("java.lang.IllegalArgumentException:\n" +
            "\tat eu.stamp.ClassA.method2(ClassA.java:10)\n" +
            "\tat eu.stamp.ClassB.method1(ClassB.java:20)"));
    StackTrace target = Mockito.spy(new StackTrace());
    Mockito.doReturn(givenStackTrace).when(target).readFromFile(anyString());
    Mockito.doReturn("java.lang.Integer").when(target).getTargetClass();
    Mockito.doReturn(1).when(target).getTargetLine();
    target.setup("", 2);
    CrashProperties.getInstance().setupStackTrace(target);

    TestChromosome clone = (TestChromosome) chromosome.clone();

    GenericAccessibleObject geObj = Mockito.mock(GenericAccessibleObject.class);
    Set<GenericAccessibleObject> publicCalls = new HashSet<>();
    publicCalls.add(geObj);

    GuidedMutation mutation = Mockito.spy(new GuidedMutation());
    mutation.updatePublicCalls(publicCalls);
    Mockito.doNothing().when(mutation).insertRandomStatement(Mockito.any(Chromosome.class));
    Mockito.doNothing().when(mutation).doRandomMutation(Mockito.any(Chromosome.class));
    mutation.mutateOffspring(chromosome);

    assertNotEquals(clone, chromosome);
}
 
Example 20
private CosmoDavException captureExceptionForErrorResponseCausedBy(Throwable t) throws Exception {
    StandardRequestHandler classUnderTest = new StandardRequestHandler(null, null, null);

    StandardRequestHandler classUnderTestSpied = Mockito.spy(classUnderTest);

    DavTestContext ctx = testHelper.createTestContext();
    HttpServletRequest req = ctx.getDavRequest();
    HttpServletResponse res = ctx.getDavResponse();

    HttpServletRequest spiedReq = Mockito.spy(req);
    Mockito.when(spiedReq.getRequestURI()).thenReturn("test/Request/Uri");

    Mockito.when(classUnderTestSpied.createDavRequest(req)).thenReturn(ctx.getDavRequest());

    DavResponse mockDavResponse = Mockito.mock(DavResponse.class);
    Mockito.when(classUnderTestSpied.createDavResponse(res)).thenReturn(mockDavResponse);

    // throw the exception here
    Mockito.doThrow(t).when(classUnderTestSpied).resolveTarget(Mockito.any(DavRequest.class));

    classUnderTestSpied.handleRequest(spiedReq, res);

    ArgumentCaptor<CosmoDavException> exceptionCaptor = ArgumentCaptor.forClass(CosmoDavException.class);
    Mockito.verify(mockDavResponse).sendDavError(exceptionCaptor.capture());

    CosmoDavException ex = exceptionCaptor.getValue();

    return ex;
}