Java Code Examples for org.mockito.invocation.InvocationOnMock#getArguments()

The following examples show how to use org.mockito.invocation.InvocationOnMock#getArguments() . 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: FileManagerTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
	Object[] args = invocation.getArguments();
	List<RPCRequest> rpcs = (List<RPCRequest>) args[0];
	OnMultipleRequestListener listener = (OnMultipleRequestListener) args[1];
	if (rpcs.get(0) instanceof PutFile) {
		Result resultCode = Result.REJECTED;
		for (RPCRequest message : rpcs) {
			int correlationId = message.getCorrelationID();
			listener.addCorrelationId(correlationId);
			PutFileResponse putFileResponse = new PutFileResponse();
			putFileResponse.setSuccess(true);
			listener.onError(correlationId, resultCode, "Binary data empty");
		}
		listener.onFinished();
	}
	return null;
}
 
Example 2
Source File: SystemCapabilityManagerTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private Answer<Void> createOnSendGetSystemCapabilityAnswer (final boolean success, final Boolean subscribe) {
	Answer<Void> onSendGetSystemCapabilityAnswer = new Answer<Void>() {
		@Override
		public Void answer(InvocationOnMock invocation) {
			Object[] args = invocation.getArguments();
			GetSystemCapability getSystemCapability = (GetSystemCapability) args[0];
			if (subscribe != null) {
				assertEquals(subscribe, getSystemCapability.getSubscribe());
			}
			GetSystemCapabilityResponse response;
			if (success) {
				response = new GetSystemCapabilityResponse(Result.SUCCESS, true);
			} else {
				response = new GetSystemCapabilityResponse(Result.REJECTED, false);
			}
			response.setSystemCapability(systemCapability);
			getSystemCapability.getOnRPCResponseListener().onResponse(CorrelationIdGenerator.generateId(), response);
			return null;
		}
	};
	return onSendGetSystemCapabilityAnswer;
}
 
Example 3
Source File: MetadataChangesOnActionsGeneratorTest.java    From data-prep with Apache License 2.0 6 votes vote down vote up
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
    final ActionContext actionContext = (ActionContext) invocation.getArguments()[0];

    // update the row metadata with the created / removed columns
    RowMetadata rowMetadata = actionContext.getRowMetadata();
    for (String addedColumn : columnsToAdd) {
        ColumnMetadata columnMetadata = createColumnNamed(addedColumn);
        rowMetadata.addColumn(columnMetadata);
    }
    for (String columnToRemove : columnsToRemove) {
        Optional<ColumnMetadata> matchingColumn = rowMetadata
                .getColumns() //
                .stream() //
                .filter(c -> columnToRemove.equals(c.getName())) //
                .findAny();
        matchingColumn.ifPresent(columnMetadata -> rowMetadata.deleteColumnById(columnMetadata.getId()));
    }

    // add stuff in the action context
    if (stuffForActionContext != null) {
        actionContext.get("rowMatcher", p -> stuffForActionContext);
    }

    return null;
}
 
Example 4
Source File: AverageTaxFactorCalculatorTestNgTest.java    From mockito-cookbook with Apache License 2.0 6 votes vote down vote up
private Answer<Object> withTaxFactorDependingOnPersonOrigin() {
	return new Answer<Object>() {			
	    @Override
	    public Object answer(InvocationOnMock invocation) throws Throwable {			    
		    double baseTaxFactor = 50;
		    double incrementedTaxFactor = 200;
	        if (invocation.getArguments().length > 0) {
	            Person person = (Person) invocation.getArguments()[0];
	            if (!person.isCountryDefined()) {
	                return incrementedTaxFactor;
	            }
	        }
	        return baseTaxFactor;
	    }
	};
}
 
Example 5
Source File: JoynrEnd2EndTest.java    From joynr with Apache License 2.0 6 votes vote down vote up
public JoynrEnd2EndTest() {
    Answer<AbstractSubscriptionPublisher> answer = new Answer<AbstractSubscriptionPublisher>() {

        @Override
        public AbstractSubscriptionPublisher answer(InvocationOnMock invocation) throws Throwable {
            Object provider = invocation.getArguments()[0];
            if (provider instanceof testProvider) {
                ((testProvider) provider).setSubscriptionPublisher(testSubscriptionPublisher);
            }
            return testSubscriptionPublisher;
        }
    };
    Mockito.doAnswer(answer)
           .when(subscriptionPublisherFactory)
           .create((JoynrProvider) Mockito.argThat(new InstanceOf(testProvider.class)));
}
 
Example 6
Source File: SDKAPIClientTest.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
    entityList = (List) invocation.getArguments()[1];

    entityList.add(getConfigMap());

    return null;
}
 
Example 7
Source File: EipSerivceJsonInvalidCertificateBackendResponse.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Answer<String> getAnswerForRequestStringFromServer() {
    return new Answer<String>() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            String url = (String) invocation.getArguments()[0];
            String requestMethod = (String) invocation.getArguments()[1];
            String jsonPayload = (String) invocation.getArguments()[2];

            if (url.contains("/provider.json")) {
                //download provider json
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"));
            } else if (url.contains("/ca.crt")) {
                //download provider ca cert
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.pem"));
            } else if (url.contains("config/eip-service.json")) {
                // download provider service json containing gateways, locations and openvpn settings
                throw new SSLHandshakeException("Invalid provider CA certificate");
            } else if (url.contains("/users.json")) {
                //create new user
                //TODO: implement me
            } else if (url.contains("/sessions.json")) {
                //srp auth: sendAToSRPServer
                //TODO: implement me
            } else if (url.contains("/sessions/parmegvtest10.json")){
                //srp auth: sendM1ToSRPServer
                //TODO: implement me
            }

            return null;
        }
    };
}
 
Example 8
Source File: IltConsumerFireAndForgetMethodTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public Void answer(InvocationOnMock invocation) throws Throwable {
    JoynrRuntimeException error = (JoynrRuntimeException) invocation.getArguments()[0];
    publicationReceivedSemaphore.release();
    fail(name.getMethodName() + " - FAILED - caught unexpected exception: " + error.getMessage());
    return null;
}
 
Example 9
Source File: PresentChoiceSetOperationTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testCancelingChoiceSetUnsuccessfullyIfThreadIsRunning(){
	when(internalInterface.getSdlMsgVersion()).thenReturn(new SdlMsgVersion(6, 0));
	presentChoiceSetOperation = new PresentChoiceSetOperation(internalInterface, choiceSet, InteractionMode.MANUAL_ONLY, null, null, choiceSetSelectionListener, Test.GENERAL_INTEGER);
	executor.execute(presentChoiceSetOperation);
	try {
		executor.awaitTermination(1, TimeUnit.SECONDS);
	} catch (InterruptedException e) {}

	assertTrue(presentChoiceSetOperation.isExecuting());
	assertFalse(presentChoiceSetOperation.isFinished());
	assertFalse(presentChoiceSetOperation.isCancelled());

	choiceSet.cancel();
	Answer<Void> cancelInteractionAnswer = new Answer<Void>() {
		@Override
		public Void answer(InvocationOnMock invocation) {
			Object[] args = invocation.getArguments();
			CancelInteraction cancelInteraction = (CancelInteraction) args[0];

			assertEquals(cancelInteraction.getCancelID(), Test.GENERAL_INTEGER);
			assertEquals(cancelInteraction.getInteractionFunctionID().intValue(), FunctionID.PERFORM_INTERACTION.getId());

			RPCResponse response = new RPCResponse(FunctionID.CANCEL_INTERACTION.toString());
			response.setSuccess(false);
			cancelInteraction.getOnRPCResponseListener().onResponse(0, response);

			return null;
		}
	};
	doAnswer(cancelInteractionAnswer).when(internalInterface).sendRPC(any(CancelInteraction.class));

	verify(internalInterface, times(1)).sendRPC(any(CancelInteraction.class));
	verify(internalInterface, times(1)).sendRPC(any(PerformInteraction.class));

	assertTrue(presentChoiceSetOperation.isExecuting());
	assertFalse(presentChoiceSetOperation.isFinished());
	assertFalse(presentChoiceSetOperation.isCancelled());
}
 
Example 10
Source File: ReplicatedTerrapinClientTest.java    From terrapin with Apache License 2.0 5 votes vote down vote up
@Override
public Future<TerrapinResponse> answer(InvocationOnMock invocationOnMock) throws Throwable {
  Set<ByteBuffer> keys = (Set<ByteBuffer>)invocationOnMock.getArguments()[1];
  TerrapinResponse response = new TerrapinResponse();
  response.setResponseMap((Map)Maps.newHashMap());
  for (ByteBuffer key : keys) {
    if (KEY_VALUE_MAP.containsKey(key)) {
      TerrapinSingleResponse singleResponse = new TerrapinSingleResponse();
      singleResponse.setValue(KEY_VALUE_MAP.get(key));
      response.getResponseMap().put(key, singleResponse);
    }
  }
  return Future.value(response);
}
 
Example 11
Source File: UpdatedCertificateBackendResponse.java    From bitmask_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Answer<String> getAnswerForRequestStringFromServer() {
    return new Answer<String>() {

        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            String url = (String) invocation.getArguments()[0];

            if (url.contains("/provider.json")) {
                if (!wasCACertCalled) {
                    throw new SSLHandshakeException("Updated certificate on server side");
                }
                //download provider json
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.net.json"));
            } else if (url.contains("/ca.crt")) {
                //download provider ca cert
                wasCACertCalled = true;
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("updated_cert.pem"));
            } else if (url.contains("config/eip-service.json")) {
                // download provider service json containing gateways, locations and openvpn settings
                if (!wasCACertCalled) {
                    throw new SSLHandshakeException("Updated certificate on server side");
                }
                return getInputAsString(getClass().getClassLoader().getResourceAsStream("riseup.service.json"));
            }

            return null;
        }
    };
}
 
Example 12
Source File: PresentChoiceSetOperationTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void testCancelingChoiceSetSuccessfullyIfThreadIsRunning(){
	when(internalInterface.getSdlMsgVersion()).thenReturn(new SdlMsgVersion(6, 0));
	presentChoiceSetOperation = new PresentChoiceSetOperation(internalInterface, choiceSet, InteractionMode.MANUAL_ONLY, null, null, choiceSetSelectionListener, Test.GENERAL_INTEGER);
	executor.execute(presentChoiceSetOperation);

	try {
		executor.awaitTermination(1, TimeUnit.SECONDS);
	} catch (InterruptedException e) {}

	assertTrue(presentChoiceSetOperation.isExecuting());
	assertFalse(presentChoiceSetOperation.isFinished());
	assertFalse(presentChoiceSetOperation.isCancelled());

	choiceSet.cancel();
	Answer<Void> cancelInteractionAnswer = new Answer<Void>() {
		@Override
		public Void answer(InvocationOnMock invocation) {
			Object[] args = invocation.getArguments();
			CancelInteraction cancelInteraction = (CancelInteraction) args[0];

			assertEquals(cancelInteraction.getCancelID(), Test.GENERAL_INTEGER);
			assertEquals(cancelInteraction.getInteractionFunctionID().intValue(), FunctionID.PERFORM_INTERACTION.getId());

			RPCResponse response = new RPCResponse(FunctionID.CANCEL_INTERACTION.toString());
			response.setSuccess(true);
			cancelInteraction.getOnRPCResponseListener().onResponse(0, response);

			return null;
		}
	};
	doAnswer(cancelInteractionAnswer).when(internalInterface).sendRPC(any(CancelInteraction.class));

	verify(internalInterface, times(1)).sendRPC(any(CancelInteraction.class));
       verify(internalInterface, times(1)).sendRPC(any(PerformInteraction.class));

       assertTrue(presentChoiceSetOperation.isExecuting());
	assertFalse(presentChoiceSetOperation.isFinished());
	assertFalse(presentChoiceSetOperation.isCancelled());
}
 
Example 13
Source File: JobEntryDialog_ConnectionLine_Test.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public String answer( InvocationOnMock invocation ) throws Throwable {
  DatabaseMeta meta = (DatabaseMeta) invocation.getArguments()[ 0 ];
  meta.setName( name );
  meta.setHostname( host );
  return name;
}
 
Example 14
Source File: FileManagerTests.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public Void answer(InvocationOnMock invocation) {
	Object[] args = invocation.getArguments();
	RPCRequest message = (RPCRequest) args[0];
	if(message instanceof PutFile){
		int correlationId = message.getCorrelationID();
		PutFileResponse putFileResponse = new PutFileResponse();
		putFileResponse.setSuccess(false);
		message.getOnRPCResponseListener().onResponse(correlationId, putFileResponse);
	}
	return null;
}
 
Example 15
Source File: LocalCapabilitiesDirectoryTest.java    From joynr with Apache License 2.0 5 votes vote down vote up
private static Answer<Future<Void>> createAddAnswerWithDiscoveryError(DiscoveryError error) {
    return new Answer<Future<Void>>() {

        @Override
        public Future<Void> answer(InvocationOnMock invocation) throws Throwable {
            Future<Void> result = new Future<Void>();
            Object[] args = invocation.getArguments();
            @SuppressWarnings("unchecked")
            CallbackWithModeledError<Void, DiscoveryError> callback = ((CallbackWithModeledError<Void, DiscoveryError>) args[0]);
            callback.onFailure(error);
            result.onSuccess(null);
            return result;
        }
    };
}
 
Example 16
Source File: PerformanceReporterTest.java    From joynr with Apache License 2.0 4 votes vote down vote up
@Before
public void setUp() throws Exception {

    // use local test server to intercept http requests sent by the reporter
    server = new LocalTestServer(null, null);
    server.register("*", mockHandler);
    server.start();

    final String serverUrl = "http://localhost:" + server.getServiceAddress().getPort();

    // set test properties manually for a better overview of
    // what is tested
    Properties properties = new Properties();

    // have to set the BPC base url manually as this is the
    // mock server which gets port settings dynamically
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCE_PROXY_CONTROLLER_BASE_URL, serverUrl);
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCE_PROXY_ID, "X.Y");
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCEPROXY_URL_FOR_BPC, "http://joyn-bpX.muc/bp");
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCEPROXY_URL_FOR_CC, "http://joyn-bpX.de/bp");
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCE_PROXY_MONITORING_FREQUENCY_MS, "100");
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCE_PROXY_SEND_LIFECYCLE_REPORT_RETRY_INTERVAL_MS, "500");
    properties.put(BounceProxyPropertyKeys.PROPERTY_BOUNCE_PROXY_MAX_SEND_SHUTDOWN_TIME_SECS, "2");

    Injector injector = Guice.createInjector(new PropertyLoadingModule(properties), new AbstractModule() {

        @Override
        protected void configure() {

            bind(ScheduledExecutorService.class).toInstance(mockExecutorService);
            bind(BounceProxyPerformanceMonitor.class).toInstance(mockPerformanceMonitor);
            bind(BounceProxyLifecycleMonitor.class).toInstance(mockLifecycleMonitor);
            bind(CloseableHttpClient.class).toInstance(HttpClients.createDefault());
        }

    });

    reporter = injector.getInstance(BounceProxyPerformanceReporter.class);

    // fake the clock for a more robust testing
    clock = new Clock();

    Answer<Void> mockScheduledExecutor = new Answer<Void>() {

        @Override
        public Void answer(final InvocationOnMock invocation) throws Throwable {

            long frequencyMs = (Long) invocation.getArguments()[2];
            Runnable runnable = (Runnable) invocation.getArguments()[0];

            clock.setFrequencyMs(frequencyMs);
            clock.setRunnable(runnable);

            return null;
        }
    };
    Mockito.doAnswer(mockScheduledExecutor)
           .when(mockExecutorService)
           .scheduleWithFixedDelay(Mockito.any(Runnable.class),
                                   Mockito.anyLong(),
                                   Mockito.anyLong(),
                                   Mockito.any(TimeUnit.class));
}
 
Example 17
Source File: CardBuilderAnswer.java    From office-365-connector-plugin with Apache License 2.0 4 votes vote down vote up
@Override
public CardBuilder answer(InvocationOnMock invocation) {
    return new CardBuilderMock(
            (Run) (invocation.getArguments())[0],
            (TaskListener) (invocation.getArguments())[1]);
}
 
Example 18
Source File: ShardRecordsIteratorTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
  return invocation.getArguments()[0];
}
 
Example 19
Source File: ReturnsArgumentAt.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
public Object answer(InvocationOnMock invocation) throws Throwable {
    validateIndexWithinInvocationRange(invocation);
    return invocation.getArguments()[actualArgumentPosition(invocation)];
}
 
Example 20
Source File: KuduIOTest.java    From beam with Apache License 2.0 4 votes vote down vote up
@Override
public FakeReader answer(InvocationOnMock invocation) {
  Object[] args = invocation.getArguments();
  return new FakeReader((KuduIO.KuduSource<Integer>) args[0]);
}