Java Code Examples for org.mockito.Mockito

The following are top voted examples for showing how to use org.mockito.Mockito. 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: osc-core   File: CreatePortGroupTaskTest.java   Source Code and License 7 votes vote down vote up
@Test
public void testExecute_WhenPortGroupIsNotFound_ThrowsException() throws Exception {
    // Arrange.
    SecurityGroup sg = registerSecurityGroup(1L, "projectId", "projectName", 1L, "sgName");
    sg.addSecurityGroupMember(newSGMWithPort(1L));

    ostRegisterPorts(sg);

    registerDomain(UUID.randomUUID().toString(), sg);

    // network element/portGroup null
    NetworkElement ne = null;
    SdnRedirectionApi redirectionApi = registerNetworkElement(ne);
    registerNetworkRedirectionApi(redirectionApi, sg.getVirtualizationConnector());

    this.exception.expect(Exception.class);
    this.exception.expectMessage(String.format("RegisterNetworkElement failed to return PortGroup"));

    CreatePortGroupTask task = this.factoryTask.create(sg);
    // Act.
    task.execute();

    // Assert.
    verify(this.em, Mockito.never()).merge(any());
}
 
Example 2
Project: rskj   File: TxValidatorMinimumGasPriceValidatorTest.java   Source Code and License 6 votes vote down vote up
@Test
public void validMinimumGasPrice() {
    Transaction tx1 = Mockito.mock(Transaction.class);
    Transaction tx2 = Mockito.mock(Transaction.class);
    Transaction tx3 = Mockito.mock(Transaction.class);

    Mockito.when(tx1.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(10));
    Mockito.when(tx2.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(11));
    Mockito.when(tx3.getGasPriceAsInteger()).thenReturn(BigInteger.valueOf(500000000));

    TxValidatorMinimuGasPriceValidator tvmgpv = new TxValidatorMinimuGasPriceValidator();


    Assert.assertTrue(tvmgpv.validate(tx1, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
    Assert.assertTrue(tvmgpv.validate(tx2, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
    Assert.assertTrue(tvmgpv.validate(tx3, null, null, BigInteger.valueOf(10), Long.MAX_VALUE, false));
}
 
Example 3
Project: hadoop   File: TestHttpExceptionUtils.java   Source Code and License 6 votes vote down vote up
@Test
public void testValidateResponseJsonErrorKnownException() throws IOException {
  Map<String, Object> json = new HashMap<String, Object>();
  json.put(HttpExceptionUtils.ERROR_EXCEPTION_JSON, IllegalStateException.class.getSimpleName());
  json.put(HttpExceptionUtils.ERROR_CLASSNAME_JSON, IllegalStateException.class.getName());
  json.put(HttpExceptionUtils.ERROR_MESSAGE_JSON, "EX");
  Map<String, Object> response = new HashMap<String, Object>();
  response.put(HttpExceptionUtils.ERROR_JSON, json);
  ObjectMapper jsonMapper = new ObjectMapper();
  String msg = jsonMapper.writeValueAsString(response);
  InputStream is = new ByteArrayInputStream(msg.getBytes());
  HttpURLConnection conn = Mockito.mock(HttpURLConnection.class);
  Mockito.when(conn.getErrorStream()).thenReturn(is);
  Mockito.when(conn.getResponseMessage()).thenReturn("msg");
  Mockito.when(conn.getResponseCode()).thenReturn(
      HttpURLConnection.HTTP_BAD_REQUEST);
  try {
    HttpExceptionUtils.validateResponse(conn, HttpURLConnection.HTTP_CREATED);
    Assert.fail();
  } catch (IllegalStateException ex) {
    Assert.assertEquals("EX", ex.getMessage());
  }
}
 
Example 4
Project: GitHub   File: ByteBufferGifDecoderTest.java   Source Code and License 6 votes vote down vote up
@Before
public void setUp() {
  MockitoAnnotations.initMocks(this);

  gifHeader = Mockito.spy(new GifHeader());
  when(parser.parseHeader()).thenReturn(gifHeader);
  when(parserPool.obtain(isA(ByteBuffer.class))).thenReturn(parser);

  when(decoderFactory.build(isA(GifDecoder.BitmapProvider.class),
      eq(gifHeader), isA(ByteBuffer.class), anyInt()))
      .thenReturn(gifDecoder);

  List<ImageHeaderParser> parsers = new ArrayList<ImageHeaderParser>();
  parsers.add(new DefaultImageHeaderParser());

  options = new Options();
  decoder =
      new ByteBufferGifDecoder(
          RuntimeEnvironment.application,
          parsers,
          bitmapPool,
          new LruArrayPool(ARRAY_POOL_SIZE_BYTES),
          parserPool,
          decoderFactory);
}
 
Example 5
Project: osc-core   File: CreatePortGroupTaskTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testExecute_WhenDomainIsNotFound_ThrowsException() throws Exception {
    // Arrange.
    SecurityGroup sg = registerSecurityGroup(1L, "projectId", "projectName", 1L, "sgName");
    sg.addSecurityGroupMember(newSGMWithPort(1L));

    ostRegisterPorts(sg);

    // domain id null
    registerDomain(null, sg);

    this.exception.expect(Exception.class);
    this.exception
    .expectMessage(String.format("A domain was not found for the project: '%s' and Security Group: '%s",
            sg.getProjectName(), sg.getName()));

    CreatePortGroupTask task = this.factoryTask.create(sg);

    // Act.
    task.execute();

    // Assert.
    verify(this.em, Mockito.never()).merge(any());
}
 
Example 6
Project: ysoserial-modified   File: MyfacesTest.java   Source Code and License 6 votes vote down vote up
private static FacesContext createMockFacesContext () throws MalformedURLException {
    FacesContext ctx = Mockito.mock(FacesContext.class);
    CompositeELResolver cer = new CompositeELResolver();
    FacesELContext elc = new FacesELContext(cer, ctx);
    ServletRequest requestMock = Mockito.mock(ServletRequest.class);
    ServletContext contextMock = Mockito.mock(ServletContext.class);
    URL url = new URL("file:///");
    Mockito.when(contextMock.getResource(Matchers.anyString())).thenReturn(url);
    Mockito.when(requestMock.getServletContext()).thenReturn(contextMock);
    Answer<?> attrContext = new MockRequestContext();
    Mockito.when(requestMock.getAttribute(Matchers.anyString())).thenAnswer(attrContext);
    Mockito.doAnswer(attrContext).when(requestMock).setAttribute(Matchers.anyString(), Matchers.any());
    cer.add(new MockELResolver(requestMock));
    cer.add(new BeanELResolver());
    cer.add(new MapELResolver());
    Mockito.when(ctx.getELContext()).thenReturn(elc);
    return ctx;
}
 
Example 7
Project: streamingpool-core   File: CompositionStreamFactoryTest.java   Source Code and License 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCreate() {
    DiscoveryService discoveryService = Mockito.mock(DiscoveryService.class);
    StreamId<Object> sourceStreamId = Mockito.mock(StreamId.class);

    Publisher<Object> sourceReactiveStream = Mockito.mock(Publisher.class);
    Publisher<Object> newReactiveStream = Mockito.mock(Publisher.class);
    Mockito.when(discoveryService.discover(sourceStreamId)).thenReturn(sourceReactiveStream);

    Function<List<Publisher<Object>>, Publisher<Object>> transformationFunction = Mockito.mock(Function.class);
    Mockito.when(transformationFunction.apply(Collections.singletonList(sourceReactiveStream)))
            .thenReturn(newReactiveStream);

    CompositionStreamId<Object, Object> compositionStreamId = new CompositionStreamId<>(sourceStreamId,
            transformationFunction);
    ErrorStreamPair<Object> optionalCompositionReactiveStream = compositionStreamFactory
            .create(compositionStreamId, discoveryService);

    assertThat(optionalCompositionReactiveStream.data()).isEqualTo(newReactiveStream);
    Mockito.verify(transformationFunction).apply(Collections.singletonList(sourceReactiveStream));
}
 
Example 8
Project: li-android-sdk-core   File: LiBaseClientTest.java   Source Code and License 6 votes vote down vote up
@Before
    public void setUp() throws Exception, LiRestResponseException {

        mContext = Mockito.mock(Activity.class);
        mMockSharedPreferences = Mockito.mock(SharedPreferences.class);
        resource = Mockito.mock(Resources.class);
        when(resource.getBoolean(anyInt())).thenReturn(true);
        when(mContext.getSharedPreferences(anyString(), anyInt())).thenReturn(mMockSharedPreferences);
        when(mMockSharedPreferences.getString(anyString(), anyString())).thenReturn("foobar");
        when(mContext.getResources()).thenReturn(resource);
        liSDKManager = LiSDKManager.init(mContext, TestHelper.getTestAppCredentials());
        liRestv2Client = mock(LiRestv2Client.class);
        MockitoAnnotations.initMocks(this);
//        when(liSDKManager.getTenant()).thenReturn("test");
        liClientManager = mock(LiClientManager.class);
        PowerMockito.mockStatic(LiRestv2Client.class);
        BDDMockito.given(LiRestv2Client.getInstance()).willReturn(liRestv2Client);
        PowerMockito.mockStatic(LiClientManager.class);
    }
 
Example 9
Project: stock-api-sdk   File: SearchCategoryTest.java   Source Code and License 6 votes vote down vote up
@Test(groups = "SearchCategory.getCategory")
public void getCategory_should_return_valid_response() {
    try {
        PowerMockito
                .when(HttpUtils.doGet(Mockito.anyString(),
                        Matchers.<Map<String, String>> any()))
                .thenReturn(TEST_CATEGORY_RESPONSE);
        SearchCategory api = new SearchCategory(config);
        SearchCategoryRequest request = new SearchCategoryRequest()
                .setCategoryId(1043).setLocale("en-US");
        StockFileCategory category = api.getCategory(request);
        Assert.assertEquals(category.getName(), "Travel");
        Assert.assertEquals(category.getId().intValue(), 1043);
        Assert.assertEquals(category.getLink(), "/Category/travel/1043");
    } catch (Exception e) {
        Assert.fail("Didn't expect the exception here!", e);
    }
}
 
Example 10
Project: InfixToObject   File: InfixToPrefixTest.java   Source Code and License 6 votes vote down vote up
/**
 * V1 BOp V2 -> BOp V1 V2
 */
@SuppressWarnings("unchecked")
@Test
public void testBinaryOperator() {
	BinaryOperatorRepresentation<Integer> binaryOperator = Mockito.mock(BinaryOperatorRepresentation.class);
	Mockito.when(binaryOperator.isOperator()).thenReturn(true);
	ValueOperatorRepresentation<Integer> value1 = Mockito.mock(ValueOperatorRepresentation.class);
	ValueOperatorRepresentation<Integer> value2 = Mockito.mock(ValueOperatorRepresentation.class);
	INPUT.add(value1);
	INPUT.add(binaryOperator);
	INPUT.add(value2);
	ArrayList<IElementRepresentation<Integer>> RESULT = convertor.convert(INPUT);
	assertEquals(binaryOperator, RESULT.get(0));
	assertEquals(value1, RESULT.get(1));
	assertEquals(value2, RESULT.get(2));
}
 
Example 11
Project: react-native-call-events   File: ReactNativeCallEventsModuleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void init_Verifies_Permissions_NoPopupWhenGranted() throws Exception {
    ReactNativeCallEventsModule instance = getInstance();

    PowerMockito.mockStatic(ContextCompat.class);
    PowerMockito.when(ContextCompat.checkSelfPermission(mockActivity, Manifest.permission.READ_PHONE_STATE))
            .thenReturn(PackageManager.PERMISSION_GRANTED);

    PowerMockito.mockStatic(ActivityCompat.class);
    PowerMockito.doNothing().when(ActivityCompat.class);
    ActivityCompat.requestPermissions(mockActivity, new String[]{Manifest.permission.READ_PHONE_STATE}, 1);

    instance.init(false, false);

    PowerMockito.verifyStatic();
    ContextCompat.checkSelfPermission(mockActivity, Manifest.permission.READ_PHONE_STATE);

    PowerMockito.verifyStatic(Mockito.never());
    ActivityCompat.requestPermissions(Mockito.any(Activity.class), Mockito.any(String[].class), Mockito.anyInt());
}
 
Example 12
Project: jira-steps-plugin   File: EditIssueStepTest.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.updateIssue(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 13
Project: oscm   File: ServiceInstanceTest.java   Source Code and License 6 votes vote down vote up
@Ignore
public void prepareRollback() throws Exception {
    // given
    ServiceInstance si = Mockito.spy(new ServiceInstance());
    si.setSubscriptionId("subscriptionId");
    si.setReferenceId("refId");
    String expectedXML = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\"><properties><entry key=\"ROLLBACK_SUBSCRIPTIONREF\">refId</entry><entry key=\"KEY2\">VALUE2</entry><entry key=\"ROLLBACK_SUBSCRIPTIONID\">subscriptionId</entry><entry key=\"KEY1\">VALUE1</entry></properties>";

    HashMap<String, String> params = new HashMap<>();
    params.put("KEY1", "VALUE1");
    params.put("KEY2", "VALUE2");

    Mockito.doReturn(params).when(si).getParameterMap();

    // when
    si.prepareRollback();

    // then
    assertEquals(expectedXML, removeFormatting(si.getRollbackParameters()));
}
 
Example 14
Project: hadoop   File: TestBPOfferService.java   Source Code and License 6 votes vote down vote up
private void waitForBlockReport(final DatanodeProtocolClientSideTranslatorPB mockNN)
    throws Exception {
  GenericTestUtils.waitFor(new Supplier<Boolean>() {
    @Override
    public Boolean get() {
      try {
        Mockito.verify(mockNN).blockReport(
            Mockito.<DatanodeRegistration>anyObject(),  
            Mockito.eq(FAKE_BPID),
            Mockito.<StorageBlockReport[]>anyObject(),
            Mockito.<BlockReportContext>anyObject());
        return true;
      } catch (Throwable t) {
        LOG.info("waiting on block report: " + t.getMessage());
        return false;
      }
    }
  }, 500, 10000);
}
 
Example 15
Project: stock-api-sdk   File: EndpointsTest.java   Source Code and License 6 votes vote down vote up
@Test(groups = "Endpoints.getSearchFilesEndpoint")
public void getSearchFilesEndpoint_should_throw_stockexception_since_the_endpoint_properties_file_is_missing() {
    PowerMockito.spy(Endpoints.class);

    try {
        PowerMockito.doReturn(null).when(Endpoints.class,
                "getResourceAsStream", Mockito.any(String.class));
    } catch (Exception e1) {
        Assert.fail(
                "Couldn't mock the Endpoints.getResourceAsStream method!",
                e1);
    }

    try {
        new Endpoints(Environment.STAGE);

        Assert.fail("Didn't expect the endpoints to get constructed without exception!");
    } catch (StockException e) {
        Assert.assertEquals(e.getMessage(),
                "Could not load the endpoint properties file");
    }
}
 
Example 16
Project: filestack-java   File: TestClient.java   Source Code and License 6 votes vote down vote up
private static void setupUploadMock(UploadService mockUploadService) {
  String jsonString = "{"
      + "'url' : 'https://s3.amazonaws.com/path',"
      + "'headers' : {"
      + "'Authorization' : 'auth_value',"
      + "'Content-MD5' : 'md5_value',"
      + "'x-amz-content-sha256' : 'sha256_value',"
      + "'x-amz-date' : 'date_value',"
      + "'x-amz-acl' : 'acl_value'"
      + "},"
      + "'location_url' : 'url'"
      + "}";

  Gson gson = new Gson();
  final UploadResponse response = gson.fromJson(jsonString, UploadResponse.class);
  Mockito
      .doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock invocation) throws Throwable {
          return Calls.response(response);
        }
      })
      .when(mockUploadService)
      .upload(Mockito.<String, RequestBody>anyMap());
}
 
Example 17
Project: osc-core   File: VSConformanceCheckMetaTaskTest.java   Source Code and License 6 votes vote down vote up
@Parameters()
public static Collection<Object[]> getTestData() throws EncryptionException {
    encryption = Mockito.mock(EncryptionApi.class);

    PowerMockito.mockStatic(StaticRegistry.class);
    Mockito.when(StaticRegistry.encryptionApi()).thenReturn(encryption);

    Mockito.when(encryption.encryptAESCTR("")).thenReturn(ENCRYPTED_PASSWORD);

    return Arrays.asList(new Object[][] {
        {UPDATE_OPENSTACK_NO_DEPLOYMENT_SPEC_VS,  createOpenstackNoDeploymentSpecGraph(UPDATE_OPENSTACK_NO_DEPLOYMENT_SPEC_VS), false},
        {UPDATE_OPENSTACK_DEPLOYMENT_SPEC_VS,  createOpenstackWithDeploymentSpecGraph(UPDATE_OPENSTACK_DEPLOYMENT_SPEC_VS), false},
        {UPDATE_OPENSTACK_LOCK_DEPLOYMENT_SPEC_FAILS_VS,  createOpenstacWhenLockingDeploymentSpecFailsGraph(UPDATE_OPENSTACK_LOCK_DEPLOYMENT_SPEC_FAILS_VS), false},
        {DELETE_OPENSTACK_WITH_DEPLOYMENT_SPECS_VS,  createDeleteOpenStackWithDeploymentSpecGraph(DELETE_OPENSTACK_WITH_DEPLOYMENT_SPECS_VS), false},
        {DELETE_OPENSTACK_WITH_OS_IMAGE_REF_VS,  createDeleteOpenStackWithOSImageRefGraph(DELETE_OPENSTACK_WITH_OS_IMAGE_REF_VS), false},
        {DELETE_OPENSTACK_WITH_OS_FLAVOR_REF_VS,  createDeleteOpenStackWithOSFlavorRefGraph(DELETE_OPENSTACK_WITH_OS_FLAVOR_REF_VS), false},
    });
}
 
Example 18
Project: oscm   File: BesDAOTest.java   Source Code and License 6 votes vote down vote up
@Test
public void setUserCredentialsInContext_INTERNAL() {
    // given
    Map<String, Setting> settings = getSettingsForMode("INTERNAL");
    BindingProvider client = Mockito.mock(BindingProvider.class);
    Map<String, String> context = new HashMap<>();
    Mockito.doReturn(context).when(client).getRequestContext();

    // when
    besDAO.setUserCredentialsInContext(client, USER, PASSWORD, settings);

    // then
    assertNull(client.getRequestContext().get(
            "username"));
    assertNull(client.getRequestContext().get(
            "password"));
    assertEquals(
            USER,
            client.getRequestContext().get(
                    BindingProvider.USERNAME_PROPERTY));
    assertEquals(
            PASSWORD,
            client.getRequestContext().get(
                    BindingProvider.PASSWORD_PROPERTY));
}
 
Example 19
Project: flink-connectors   File: FlinkPravegaWriterTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests the close method of the transactional writer.
 */
@Test
public void testTransactionalWriterClose() throws Exception {
    try (TransactionalWriterTestContext context = new TransactionalWriterTestContext(PravegaWriterMode.EXACTLY_ONCE)) {
        Transaction<Integer> trans = context.prepareTransaction();
        try {
            try (StreamSinkOperatorTestHarness<Integer> testHarness = createTestHarness(context.sinkFunction)) {
                testHarness.open();

                // prepare a worst-case situation that exercises the exception handling aspect of close
                Mockito.doThrow(new IntentionalRuntimeException()).when(trans).abort();
                Mockito.doThrow(new IntentionalRuntimeException()).when(context.pravegaWriter).close();
            }
            Assert.fail("expected an exception");
        } catch (IntentionalRuntimeException e) {
            Assert.assertEquals(1, e.getSuppressed().length);
            Assert.assertTrue(e.getSuppressed()[0] instanceof IntentionalRuntimeException);
        }

        // verify that the transaction was aborted and the writer closed
        verify(trans).abort();
        verify(context.pravegaWriter).close();
    }
}
 
Example 20
Project: hadoop-oss   File: TestFailoverController.java   Source Code and License 6 votes vote down vote up
@Test
public void testFailbackToFaultyServiceFails() throws Exception {
  DummyHAService svc1 = new DummyHAService(HAServiceState.ACTIVE, svc1Addr);
  Mockito.doThrow(new ServiceFailedException("Failed!"))
      .when(svc1.proxy).transitionToActive(anyReqInfo());
  DummyHAService svc2 = new DummyHAService(HAServiceState.STANDBY, svc2Addr);
  Mockito.doThrow(new ServiceFailedException("Failed!"))
      .when(svc2.proxy).transitionToActive(anyReqInfo());

  svc1.fencer = svc2.fencer = setupFencer(AlwaysSucceedFencer.class.getName());

  try {
    doFailover(svc1, svc2, false, false);
    fail("Failover to already active service");
  } catch (FailoverFailedException ffe) {
    // Expected
  }

  assertEquals(HAServiceState.STANDBY, svc1.state);
  assertEquals(HAServiceState.STANDBY, svc2.state);
}
 
Example 21
Project: keti   File: PolicyManagementServiceTest.java   Source Code and License 6 votes vote down vote up
public void testCreatePolicySetsForMultipleZones() {
    PolicySet issuer1PolicySet = this.jsonUtils.deserializeFromFile("set-with-1-policy.json", PolicySet.class);
    PolicySet issuer2PolicySet = this.jsonUtils
            .deserializeFromFile("policy-set-with-one-policy-one-condition.json", PolicySet.class);

    Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone1);
    this.policyService.upsertPolicySet(issuer1PolicySet);

    Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone2);
    this.policyService.upsertPolicySet(issuer2PolicySet);

    Assert.assertEquals(this.policyService.getAllPolicySets().size(), 1);

    this.policyService.deletePolicySet(issuer2PolicySet.getName());
    // need this to delete issuer1PolicySet properly (policy-set-id and
    // zone_id are used to find the row)
    Mockito.when(this.mockZoneResolver.getZoneEntityOrFail()).thenReturn(this.zone1);
    this.policyService.deletePolicySet(issuer1PolicySet.getName());
    Assert.assertEquals(this.policyService.getAllPolicySets().size(), 0);

}
 
Example 22
Project: aws-codecommit-trigger-plugin   File: SQSQueueMonitorSchedulerImplTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldStopMonitorOnConfigurationChangedIfQueueRemoved() {
    this.scheduler.register(this.listenerA1);
    this.scheduler.register(this.listenerB1);
    Mockito.verify(this.factory).createMonitor(this.executor, this.queueA);
    Mockito.verify(this.factory).createMonitor(this.executor, this.queueB);
    Mockito.verify(this.monitorA, times(1)).add(this.listenerA1);
    Mockito.verify(this.monitorB, times(1)).add(this.listenerB1);
    Mockito.when(this.provider.getSqsQueue(UUID_B)).thenReturn(null);

    this.scheduler.onConfigurationChanged(new ConfigurationChangedEvent());

    Mockito.verifyNoMoreInteractions(this.factory);
    Mockito.verify(this.monitorA).getQueue();
    Mockito.verify(this.monitorA).isShutDown();
    Mockito.verify(this.monitorB).shutDown();
    Mockito.verifyNoMoreInteractions(this.monitorA);
    Mockito.verifyNoMoreInteractions(this.monitorB);
}
 
Example 23
Project: Enjin-Coin-Java-SDK   File: EventsServiceTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({ "unchecked", "serial" })
@Test
public void testGetEvent_AppIdIsNull() throws Exception {
    GetEventRequestVO getEventRequestVO = ImmutableGetEventRequestVO.builder()
            .setAppId((String) null)
            .setEventId("eventId")
            .setIdentityMap(new HashMap<String, Object>() {{put("uuid", "069a79f4-44e9-4726-a5be-fca90e38aaf5");}})
            .setAfterEventId("123456789")
            .setBeforeEventId("123456789")
            .setLimit("50")
            .build();

    GetEventResponseVO returnedGetEventResponseVO = ImmutableGetEventResponseVO.builder().build();
    GetEventResponseVO[] returnedGetEventResponseArray = new GetEventResponseVO[] {returnedGetEventResponseVO};

    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(returnedGetEventResponseArray);

    eventService = new EventsServiceImpl(enjinConfig);
    GetEventResponseVO[] getEventResponseVO = eventService.getEvent(getEventRequestVO);
    assertThat(getEventResponseVO).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 24
Project: jmeter-bzm-plugins   File: HlsSamplerTest.java   Source Code and License 6 votes vote down vote up
@Before
	public void setup()
	        throws Exception {
//        TestJMeterUtils.createJmeterEnv();
		
        parserMock = Mockito.mock(Parser.class);
        sampler = new HlsSampler();
		sampler.setURLData("http://www.mock.com/path");
		sampler.setResData("640x360");
		sampler.setNetworkData("1395723");
		sampler.setBandwidthType("customBandwidth");
		sampler.setResolutionType("customResolution");
		sampler.setUrlVideoType("Bandwidth");
		sampler.setPRotocol("https");
		sampler.setPlaySecondsData("20");
		sampler.setVideoDuration(true);
		sampler.setParser(parserMock);
		sampler.setName("Test");
	}
 
Example 25
Project: Enjin-Coin-Java-SDK   File: IdentitiesAsyncServiceTest.java   Source Code and License 6 votes vote down vote up
@SuppressWarnings({"unchecked", "serial"})
@Test
public void testCreateIdentity_Success() throws Exception {
    CreateIdentityRequestVO createIdentityRequestVO = ImmutableCreateIdentityRequestVO.builder()
            .setAuth("auth")
            .setIdentityMap(new HashMap<String, Object>() {{
                put("key", "value");
            }})
            .build();

    CreateIdentityResponseVO returnedCreateIdentityResponseVO = ImmutableCreateIdentityResponseVO.builder().build();

    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(returnedCreateIdentityResponseVO);

    identitiesAsyncService = new IdentitiesAsyncServiceImpl(enjinConfig);
    CompletableFuture<CreateIdentityResponseVO> createIdentityResponseCompletableFutureVO = identitiesAsyncService.createIdentityAsync(createIdentityRequestVO);
    assertThat(createIdentityResponseCompletableFutureVO).isNotNull();
    CreateIdentityResponseVO createIdentityResponseVO = createIdentityResponseCompletableFutureVO.get();
    assertThat(createIdentityResponseVO).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 26
Project: osc-core   File: MgrSecurityGroupInterfaceCheckMetaTaskTestData.java   Source Code and License 6 votes vote down vote up
private static SecurityGroupInterface createSgi(String sgiId, String sgiName, boolean isMarkedForDeletion,
        String tag, String policyId) {
    SecurityGroupInterface sgi = Mockito.mock(SecurityGroupInterface.class);
    Mockito.when(sgi.getMgrSecurityGroupInterfaceId()).thenReturn(sgiId);
    Mockito.when(sgi.getName()).thenReturn(sgiName);
    Mockito.when(sgi.getMarkedForDeletion()).thenReturn(isMarkedForDeletion);
    Mockito.when(sgi.getTag()).thenReturn(tag);
    Policy policy = Mockito.mock(Policy.class);
    Set<Policy> policySet = new HashSet<>();
    policySet.add(policy);
    Mockito.when(sgi.getMgrPolicies()).thenReturn(policySet);
    Mockito.when(policy.getMgrPolicyId()).thenReturn(policyId);

    return sgi;

}
 
Example 27
Project: server   File: GenerationTestIT.java   Source Code and License 6 votes vote down vote up
@Test
public void step_3_generate_block() throws Exception {

	PeerContext ctx = new PeerContext(GENERATOR, mockTimeProvider);
	Block lastBlock = ctx.context.getInstance().getBlockchainService().getLastBlock();

	Mockito.when(mockTimeProvider.get()).thenReturn(lastBlock.getTimestamp() + 200);

	ctx.generateBlockForNow();

	Assert.assertNotEquals("Is new block generated", lastBlock.getID(),
			ctx.context.getInstance().getBlockchainService().getLastBlock().getID());
	Assert.assertFalse("Generator stopped", ctx.context.getInstance().getGenerator().isGenerationAllowed());

	Block generatedBlock = ctx.context.getInstance().getBlockchainService()
			.getBlock(ctx.context.getInstance().getBlockchainService().getLastBlock().getID());

	Assert.assertEquals("DB store new block ID", generatedBlock.getID(),
			ctx.context.getInstance().getBlockchainService().getLastBlock().getID());
	Assert.assertEquals("Period is 180 sec", lastBlock.getTimestamp() + 180, generatedBlock.getTimestamp());
}
 
Example 28
Project: hadoop   File: TestNodesPage.java   Source Code and License 5 votes vote down vote up
@Test
public void testNodesBlockRenderForNodeLabelFilterWithAnyLabel() {
  NodesBlock nodesBlock = injector.getInstance(NodesBlock.class);
  nodesBlock.set("node.label", "*");
  nodesBlock.render();
  PrintWriter writer = injector.getInstance(PrintWriter.class);
  WebAppTests.flushOutput(injector);

  Mockito.verify(
      writer,
      Mockito.times(numberOfRacks * numberOfNodesPerRack
          * numberOfActualTableHeaders + numberOfThInMetricsTable)).print(
      "<td");
}
 
Example 29
Project: hadoop   File: TestActiveStandbyElector.java   Source Code and License 5 votes vote down vote up
/**
 * Verify that, when the callback fails to enter active state, after
 * a ZK disconnect (i.e from the StatCallback), that the elector rejoins
 * the election after sleeping for a short period.
 */
@Test
public void testFailToBecomeActiveAfterZKDisconnect() throws Exception {
  mockNoPriorActive();
  elector.joinElection(data);
  Assert.assertEquals(0, elector.sleptFor);

  elector.processResult(Code.CONNECTIONLOSS.intValue(), ZK_LOCK_NAME, mockZK,
      ZK_LOCK_NAME);
  Mockito.verify(mockZK, Mockito.times(2)).create(ZK_LOCK_NAME, data,
      Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);

  elector.processResult(Code.NODEEXISTS.intValue(), ZK_LOCK_NAME, mockZK,
      ZK_LOCK_NAME);
  verifyExistCall(1);

  Stat stat = new Stat();
  stat.setEphemeralOwner(1L);
  Mockito.when(mockZK.getSessionId()).thenReturn(1L);

  // Fake failure to become active from within the stat callback
  Mockito.doThrow(new ServiceFailedException("fail to become active"))
      .when(mockApp).becomeActive();
  elector.processResult(Code.OK.intValue(), ZK_LOCK_NAME, mockZK, stat);
  Mockito.verify(mockApp, Mockito.times(1)).becomeActive();
  
  // should re-join
  Mockito.verify(mockZK, Mockito.times(3)).create(ZK_LOCK_NAME, data,
      Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL, elector, mockZK);
  Assert.assertEquals(2, count);
  Assert.assertTrue(elector.sleptFor > 0);
}
 
Example 30
Project: joal   File: TrackerClientTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldDoNothingOnClose() {
    final DefaultTrackerClient trackerClient = Mockito.mock(DefaultTrackerClient.class);
    Mockito.doCallRealMethod().when(trackerClient).close();
    try {
        trackerClient.close();
    } catch (final Throwable ignored) {
        fail("should not fail to close.");
    }
}
 
Example 31
Project: hashsdn-controller   File: RefreshingSCPModuleInfoRegistryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConstructor() throws Exception {
    final ModuleInfoRegistry reg = mock(ModuleInfoRegistry.class);
    final SchemaContextProvider prov = mock(SchemaContextProvider.class);
    doReturn("string").when(prov).toString();
    final BundleContext ctxt = mock(BundleContext.class);
    final ServiceRegistration<?> servReg = mock(ServiceRegistration.class);
    doReturn(servReg).when(ctxt).registerService(any(Class.class), any(SchemaContextProvider.class),
            any(Dictionary.class));
    doReturn(servReg).when(ctxt).registerService(Mockito.anyString(), any(Object.class), any(Dictionary.class));
    doNothing().when(servReg).setProperties(any(Dictionary.class));

    final ClassLoadingStrategy classLoadingStrat = mock(ClassLoadingStrategy.class);
    final BindingContextProvider codecRegistryProvider = mock(BindingContextProvider.class);
    doNothing().when(codecRegistryProvider).update(classLoadingStrat, prov);
    final BindingRuntimeContext bindingRuntimeContext = mock(BindingRuntimeContext.class);
    doReturn("B-runtime-context").when(bindingRuntimeContext).toString();
    doReturn(bindingRuntimeContext).when(codecRegistryProvider).getBindingContext();

    final RefreshingSCPModuleInfoRegistry scpreg = new RefreshingSCPModuleInfoRegistry(reg, prov, classLoadingStrat,
            this.sourceProvider, codecRegistryProvider, ctxt);

    doNothing().when(servReg).unregister();

    final YangModuleInfo modInfo = mock(YangModuleInfo.class);
    doReturn("").when(modInfo).toString();
    final ObjectRegistration<YangModuleInfo> ymi = mock(ObjectRegistration.class);
    doReturn(ymi).when(reg).registerModuleInfo(modInfo);

    scpreg.registerModuleInfo(modInfo);
    scpreg.updateService();

    verify(codecRegistryProvider).update(classLoadingStrat, prov);

    scpreg.close();

    Mockito.verify(servReg, Mockito.times(1)).setProperties(any(Dictionary.class));
    Mockito.verify(servReg, Mockito.times(1)).unregister();
}
 
Example 32
Project: hadoop   File: TestBlockManager.java   Source Code and License 5 votes vote down vote up
private BlockInfoContiguous addBlockOnNodes(long blockId, List<DatanodeDescriptor> nodes) {
  BlockCollection bc = Mockito.mock(BlockCollection.class);
  Mockito.doReturn((short)3).when(bc).getBlockReplication();
  BlockInfoContiguous blockInfo = blockOnNodes(blockId, nodes);

  bm.blocksMap.addBlockCollection(blockInfo, bc);
  return blockInfo;
}
 
Example 33
Project: oscm   File: SamlKeySelectorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void algorithmCompatibleWithMethod_rsa() {
    // given
    SamlKeySelector keySelector = mock(SamlKeySelector.class,
            Mockito.CALLS_REAL_METHODS);

    // when
    boolean result = keySelector.algorithmCompatibleWithMethod(
            SignatureMethod.RSA_SHA1, keySelector.ALGORITHM_RSA);

    // then
    assertTrue(result);
}
 
Example 34
Project: firebase-admin-java   File: PersistentConnectionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOnDisconnectCancel() throws InterruptedException {
  MockConnectionFactory connFactory = new MockConnectionFactory();
  connFactory.persistentConn.onReady(System.currentTimeMillis(), "last-session-id");
  connFactory.persistentConn.onDataMessage(
      ImmutableMap.<String, Object>of("r", 1, "b", ImmutableMap.of("s", "ok")));

  RequestResultCallback callback = Mockito.mock(RequestResultCallback.class);
  connFactory.persistentConn.onDisconnectCancel(ImmutableList.of("put"), callback);

  // Write should not be sent until auth us successful
  assertEquals(3, connFactory.outgoing.size());
  assertEquals("oc", connFactory.outgoing.get(2).getAction());
}
 
Example 35
Project: oscm   File: ServiceProvisioningSuspendResumeServiceTest.java   Source Code and License 5 votes vote down vote up
@Test(expected = OperationNotPermittedException.class)
public void resumeService_CatalogEntriesEmpty() throws Exception {
    try {
        product.setCatalogEntries(new ArrayList<CatalogEntry>());
        bean.resumeService(voService);
    } finally {
        Mockito.verify(dataServiceMock, Mockito.never()).flush();
    }
}
 
Example 36
Project: MMORPG_Prototype   File: LayerCollisionMapTests.java   Source Code and License 5 votes vote down vote up
@Test(expected = OutOfBoundsException.class)
public void insertObjectOnBorder5_5_thenMoveDown_shouldThrowOutOfBoundsException()
{
	Mockito
	.when(object.getCenter())
	.thenReturn(calcPosition(5, 5)); 
	collisionMap.insert(object);
	collisionMap.moveDown(object);
}
 
Example 37
Project: hadoop   File: TestDFSHAAdmin.java   Source Code and License 5 votes vote down vote up
@Test
public void testFailoverWithFencerConfigured() throws Exception {
  Mockito.doReturn(STANDBY_READY_RESULT).when(mockProtocol).getServiceStatus();
  HdfsConfiguration conf = getHAConf();
  conf.set(DFSConfigKeys.DFS_HA_FENCE_METHODS_KEY, getFencerTrueCommand());
  tool.setConf(conf);
  assertEquals(0, runTool("-failover", "nn1", "nn2"));
}
 
Example 38
Project: bootstrap   File: CryptoHelperTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test encrypt.
 */
@Test
public void encryptAsNeeded() {
	final StringEncryptor stringEncryptor = Mockito.mock(StringEncryptor.class);
	Mockito.when(stringEncryptor.decrypt("value")).thenThrow(new EncryptionOperationNotPossibleException());
	Mockito.when(stringEncryptor.encrypt("value")).thenReturn("encrypted");
	final CryptoHelper securityHelper = new CryptoHelper();
	securityHelper.setEncryptor(stringEncryptor);
	Assert.assertEquals("encrypted", securityHelper.encryptAsNeeded("value"));
}
 
Example 39
Project: osc-core   File: DeleteServiceFunctionChainServiceTest.java   Source Code and License 5 votes vote down vote up
@Override
@Before
public void testInitialize() throws Exception {
	super.testInitialize();
	this.service.validator = this.validatorMock;
	this.request = new BaseIdRequest();
	Mockito.when(this.service.validator.create(this.em)).thenReturn(this.validatorMock);
}
 
Example 40
Project: osc-core   File: UpdateK8sSecurityGroupMemberLabelMetaTaskTest.java   Source Code and License 5 votes vote down vote up
@Before
public void testInitialize() throws VmidcException {
    MockitoAnnotations.initMocks(this);
    this.em = InMemDB.getEntityManagerFactory().createEntityManager();

    this.txControl.setEntityManager(this.em);
    Mockito.when(this.dbMgr.getTransactionalEntityManager()).thenReturn(this.em);
    Mockito.when(this.dbMgr.getTransactionControl()).thenReturn(this.txControl);
    registerKubernetesPods(this.sgm.getLabel(), MATCHING_PODS);
    persist(this.sgm, this.em);
}
 
Example 41
Project: powsybl-core   File: StaticVarCompensatorsValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkNetworkSvcs() {
    Network network = Mockito.mock(Network.class);
    Mockito.when(network.getId()).thenReturn("network");
    Mockito.when(network.getStaticVarCompensatorStream()).thenAnswer(dummy -> Stream.of(svc));

    assertTrue(StaticVarCompensatorsValidation.checkSVCs(network, looseConfig, NullWriter.NULL_WRITER));
}
 
Example 42
Project: cf-mta-deploy-service   File: ApplicationStagingStateGetterTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);
    this.response = TestUtil.getResourceAsString(responseLocation, getClass());
    Mockito.when(restTemplateFactory.getRestTemplate(client)).thenReturn(restTemplate);
    Mockito.when(restTemplate.getForObject(APP_URL, String.class)).thenReturn(response);
    Mockito.when(client.getCloudControllerUrl()).thenReturn(new URL(CONTROLLER_URL));
    Mockito.when(client.getApplication(APP_NAME)).thenReturn(APP);
}
 
Example 43
Project: incubator-servicecomb-java-chassis   File: TestSSLSocketFactoryExt.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  SSLSocketFactory factory = Mockito.mock(SSLSocketFactoryExt.class);
  String[] ciphers = {"test"};

  String[] protos = {"test"};
  instance = new SSLSocketFactoryExt(factory, ciphers, protos);
}
 
Example 44
Project: aws-sdk-java-v2   File: RetryableAssertionTest.java   Source Code and License 5 votes vote down vote up
@Test
public void assertCallableThrowsException_DoesNotContinueRetrying() throws Exception {
    Mockito.when(callable.call())
            .thenThrow(new IOException("Unexpected exception in assert logic"));
    try {
        doRetryableAssert();
        fail("Expected IOException");
    } catch (IOException expected) {
    }
    Mockito.verify(callable, Mockito.times(1)).call();
}
 
Example 45
Project: summer-mqtt   File: MqttClientEventPublisherTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testPublishConnectedEventNullServerUri()
{
    thrown.expect(IllegalArgumentException.class);
    thrown.expectMessage("'serverUri' must be set!");
    ApplicationEventPublisher applicationEventPublisher = Mockito
        .mock(ApplicationEventPublisher.class);
    mqttClientEventPublisher.publishConnectedEvent(CLIENT_ID, null, SUBSCRIBED_TOPICS_EMPTY,
        applicationEventPublisher, this);
}
 
Example 46
Project: cf-mta-deploy-service   File: MtaConfigurationPurgerTest.java   Source Code and License 5 votes vote down vote up
private void initConfigurationEntriesMock() {
    configurationEntries.add(createEntry(ENTRY_ID_TO_REMOVE, "remove:true"));
    configurationEntries.add(createEntry(ENTRY_ID_TO_KEEP_1, "anatz:dependency-1"));
    configurationEntries.add(createEntry(ENTRY_ID_TO_KEEP_2, "anatz:dependency-2"));
    Mockito.when(entryDao.find(ConfigurationEntriesUtil.PROVIDER_NID, null, null, new CloudTarget(TARGET_ORG, TARGET_SPACE), null,
        null)).thenReturn(configurationEntries);
}
 
Example 47
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 licensing information for the asset")
public void downloadAsset_should_throw_exception_since_license_info_null() throws Exception{
    PowerMockito
    .when(HttpUtils.doGet(Mockito.anyString(),
            Matchers.<Map<String, String>> any()))
    .thenReturn("null");
    License api = new License(config);
    api.downloadAsset(new LicenseRequest().setContentId(84071201).setLicenseState(AssetLicenseState.STANDARD), "accessToken");
}
 
Example 48
Project: cereebro   File: EurekaSnitchRegistryTest.java   Source Code and License 5 votes vote down vote up
@Test
public void discoveryClientWithOneEurekaServiceInstance() {
    EurekaServiceInstance serviceInstance = Mockito.mock(EurekaServiceInstance.class);
    Mockito.when(discoveryClient.getServices()).thenReturn(Lists.newArrayList("serviceId"));
    Mockito.when(discoveryClient.getInstances("serviceId")).thenReturn(Lists.newArrayList(serviceInstance));
    Mockito.when(serviceInstance.getMetadata())
            .thenReturn(Maps.newHashMap(CereebroMetadata.KEY_SNITCH_URI, "http://localhost:8080/cereebro"));
    DiscoveryClientSnitchRegistry snitchR = new DiscoveryClientSnitchRegistry(discoveryClient, objectMapper);
    List<Snitch> snitches = snitchR.getAll();
    Assertions.assertThat(snitches).isNotEmpty();
    Assertions.assertThat(snitches).hasSize(1);
}
 
Example 49
Project: hadoop-oss   File: TestRestCsrfPreventionFilter.java   Source Code and License 5 votes vote down vote up
@Test
public void testHeaderPresentDefaultConfig_goodRequest()
    throws ServletException, IOException {
  // Setup the configuration settings of the server
  FilterConfig filterConfig = Mockito.mock(FilterConfig.class);
  Mockito.when(filterConfig.getInitParameter(
    RestCsrfPreventionFilter.CUSTOM_HEADER_PARAM)).thenReturn(null);
  Mockito.when(filterConfig.getInitParameter(
    RestCsrfPreventionFilter.CUSTOM_METHODS_TO_IGNORE_PARAM)).
    thenReturn(null);

  // CSRF HAS been sent
  HttpServletRequest mockReq = Mockito.mock(HttpServletRequest.class);
  Mockito.when(mockReq.getHeader(RestCsrfPreventionFilter.HEADER_DEFAULT)).
    thenReturn("valueUnimportant");

  // Objects to verify interactions based on request
  HttpServletResponse mockRes = Mockito.mock(HttpServletResponse.class);
  FilterChain mockChain = Mockito.mock(FilterChain.class);

  // Object under test
  RestCsrfPreventionFilter filter = new RestCsrfPreventionFilter();
  filter.init(filterConfig);
  filter.doFilter(mockReq, mockRes, mockChain);

  Mockito.verify(mockChain).doFilter(mockReq, mockRes);
}
 
Example 50
Project: filestack-java   File: TestFileLink.java   Source Code and License 5 votes vote down vote up
/** Set networking singletons to mocks. */
@Before
public void setup() {
  CdnService mockCdnService = Mockito.mock(CdnService.class);
  BaseService mockBaseService = Mockito.mock(BaseService.class);
  Networking.setCdnService(mockCdnService);
  Networking.setBaseService(mockBaseService);
}
 
Example 51
Project: bootstrap   File: CryptoHelperTest.java   Source Code and License 5 votes vote down vote up
/**
 * Test encrypt an encrypted value.
 */
@Test
public void encryptAsNeededAlreadyEncrypted() {
	final StringEncryptor stringEncryptor = Mockito.mock(StringEncryptor.class);
	Mockito.when(stringEncryptor.decrypt("encrypted")).thenReturn("value");
	final CryptoHelper securityHelper = new CryptoHelper();
	securityHelper.setEncryptor(stringEncryptor);
	Assert.assertEquals("encrypted", securityHelper.encryptAsNeeded("encrypted"));
}
 
Example 52
Project: pokeraidbot   File: RaidPokemonsTest.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    UserConfigRepository userConfigRepository = Mockito.mock(UserConfigRepository.class);
    when(userConfigRepository.findOne(any(String.class))).thenReturn(null);
    localeService = new LocaleService("sv", userConfigRepository);
    pokemonRepository = new PokemonRepository("/pokemons.csv", localeService);
    strategyService = new PokemonRaidStrategyService(pokemonRepository);
}
 
Example 53
Project: aws-xray-sdk-java   File: AWSXRayRecorderTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDummySegmentNotEmitted() {
    Emitter mockEmitter = Mockito.mock(UDPEmitter.class);
    AWSXRayRecorder recorder = AWSXRayRecorderBuilder.standard().withEmitter(mockEmitter).build();

    recorder.beginDummySegment();
    recorder.beginSubsegment("test");
    recorder.endSubsegment();
    recorder.endSegment();

    Mockito.verify(mockEmitter, Mockito.times(0)).sendSegment(Mockito.any());
}
 
Example 54
Project: powsybl-core   File: StaticVarCompensatorsValidationTest.java   Source Code and License 5 votes vote down vote up
@Test
public void checkSvcs() {
    // active power should be equal to 0
    assertTrue(StaticVarCompensatorsValidation.checkSVCs(svc, strictConfig, NullWriter.NULL_WRITER));
    Mockito.when(svcTerminal.getP()).thenReturn(-39.8f);
    assertFalse(StaticVarCompensatorsValidation.checkSVCs(svc, strictConfig, NullWriter.NULL_WRITER));

    // the unit is disconnected
    Mockito.when(svcBusView.getBus()).thenReturn(null);
    assertTrue(StaticVarCompensatorsValidation.checkSVCs(svc, strictConfig, NullWriter.NULL_WRITER));
}
 
Example 55
Project: java-microservice   File: EmailCommandHandlerTest.java   Source Code and License 5 votes vote down vote up
@Test
public void create() throws Exception {
    String uuid = UUID.randomUUID().toString();
    EmailCreateCommand command = new EmailCreateCommand(
            uuid,
            new Email("Alexsandro", "[email protected]", EmailState.CREATED)
    );
    commandHandler.create(command);
    verify(eventPublisher, Mockito.times(1)).publish(Mockito.anyObject());
    verify(eventPublisher, Mockito.times(1)).stream(Mockito.anyObject());
}
 
Example 56
Project: osc-core   File: ListServiceFunctionChainByVcServiceTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testDispatch_WhenRequestIsValid_ValidationSucceeds() throws Exception {
	Mockito.when(this.service.validator.validateVirtualConnector(this.em, this.vc.getId())).thenCallRealMethod();
	this.request.setId(this.vc.getId());
	// Act.
	ListResponse<ServiceFunctionChainDto> response = this.service.dispatch(this.request);
	Assert.assertNotNull("The returned response should not be null.", response);

}
 
Example 57
Project: f5-marathon-autoscale   File: MarathonSDServiceUnitTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldNotReturnServiceDetailsIfLabelSectionNotPresent() throws Exception {
    String marathonResponse = Fixtures.getJSONFromFile("marathon/noautoscaleservice_without_label_section.json");
    Mockito.when(marathonGateway.getMarathonServiceDetails()).thenReturn(marathonResponse);
    marathonSDService.updateServiceData();
    assertThat(marathonSDService.getAutoScaleServicesNames().size(), is(0));
    verify(marathonGateway, times(1)).getMarathonServiceDetails();
}
 
Example 58
Project: ditb   File: TestDefaultStoreEngine.java   Source Code and License 5 votes vote down vote up
@Test
public void testCustomParts() throws Exception {
  Configuration conf = HBaseConfiguration.create();
  conf.set(DefaultStoreEngine.DEFAULT_COMPACTOR_CLASS_KEY, DummyCompactor.class.getName());
  conf.set(DefaultStoreEngine.DEFAULT_COMPACTION_POLICY_CLASS_KEY,
      DummyCompactionPolicy.class.getName());
  conf.set(DefaultStoreEngine.DEFAULT_STORE_FLUSHER_CLASS_KEY,
      DummyStoreFlusher.class.getName());
  Store mockStore = Mockito.mock(Store.class);
  StoreEngine<?, ?, ?, ?> se = StoreEngine.create(mockStore, conf, new KVComparator());
  Assert.assertTrue(se instanceof DefaultStoreEngine);
  Assert.assertTrue(se.getCompactionPolicy() instanceof DummyCompactionPolicy);
  Assert.assertTrue(se.getStoreFlusher() instanceof DummyStoreFlusher);
  Assert.assertTrue(se.getCompactor() instanceof DummyCompactor);
}
 
Example 59
Project: java-ilp-plugin   File: AbstractMockLedgerPluginTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testConnect() throws Exception {
  // The test connects the plugin to the ledger by default, so disconnect first.
  this.mockLedgerPlugin.disconnect();
  Mockito.reset(ledgerPluginEventHandlerMock);

  this.mockLedgerPlugin.connect();
  assertThat(mockLedgerPlugin.isConnected(), is(true));

  verify(ledgerPluginEventHandlerMock).onConnect(any());
  verifyNoMoreInteractions(ledgerPluginEventHandlerMock);
  assertThat(mockLedgerPlugin.getSimulatedLedger().getConnections().size(), is(1));
}
 
Example 60
Project: AndroidVideoCache   File: HttpProxyCacheTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testProcessPartialRequestWithoutCache() throws Exception {
    FileCache fileCache = new FileCache(ProxyCacheTestUtils.newCacheFile());
    FileCache spyFileCache = Mockito.spy(fileCache);
    doThrow(new RuntimeException()).when(spyFileCache).read(any(byte[].class), anyLong(), anyInt());

    String httpRequest = "GET /" + HTTP_DATA_URL + " HTTP/1.1\nRange: bytes=2000-";
    Response response = processRequest(HTTP_DATA_URL, httpRequest, spyFileCache);

    byte[] fullData = loadTestData();
    byte[] partialData = new byte[fullData.length - 2000];
    System.arraycopy(fullData, 2000, partialData, 0, partialData.length);
    assertThat(response.data).isEqualTo(partialData);
    assertThat(response.code).isEqualTo(206);
}