org.mockito.MockedStatic.when()

Here are the examples of the java api org.mockito.MockedStatic.when() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

112 Examples 7

19 Source : JSchExecutorTests.java
with Apache License 2.0
from vividus-framework

@Test
void shouldExecuteSuccessfullyWithAgentForwarding() throws AgentProxyException, JSchException, CommandExecutionException {
    ServerConfiguration server = getDefaultServerConfiguration();
    server.setAgentForwarding(true);
    Session session = mock(Session.clreplaced);
    Connector connector = mock(Connector.clreplaced);
    try (MockedStatic<ConnectorFactory> connectorFactoryMock = mockStatic(ConnectorFactory.clreplaced);
        MockedConstruction<JSch> jSchMock = mockConstruction(JSch.clreplaced, (mock, context) -> when(mock.getSession(server.getUsername(), server.getHost(), server.getPort())).thenReturn(session));
        MockedConstruction<RemoteIdenreplacedyRepository> remoteIdenreplacedyRepositoryMock = mockConstruction(RemoteIdenreplacedyRepository.clreplaced, (mock, context) -> {
            replacedertEquals(1, context.getCount());
            replacedertEquals(List.of(connector), context.arguments());
        })) {
        ConnectorFactory connectorFactory = mock(ConnectorFactory.clreplaced);
        connectorFactoryMock.when(ConnectorFactory::getDefault).thenReturn(connectorFactory);
        when(connectorFactory.createConnector()).thenReturn(connector);
        ChannelExec channelExec = mockChannelOpening(session);
        SshOutput actual = new TestJSchExecutor().execute(server, COMMANDS);
        replacedertEquals(SSH_OUTPUT, actual);
        JSch jSch = jSchMock.constructed().get(0);
        InOrder ordered = inOrder(jSch, session, channelExec);
        ordered.verify(jSch).setIdenreplacedyRepository(remoteIdenreplacedyRepositoryMock.constructed().get(0));
        verifyFullConnection(ordered, server, session, channelExec);
    }
}

19 Source : S3BucketStepsTests.java
with Apache License 2.0
from vividus-framework

void testSteps(FailableConsumer<S3BucketSteps, IOException> test) throws IOException {
    try (MockedStatic<AmazonS3ClientBuilder> clientBuilder = mockStatic(AmazonS3ClientBuilder.clreplaced)) {
        clientBuilder.when(AmazonS3ClientBuilder::defaultClient).thenReturn(amazonS3Client);
        S3BucketSteps steps = new S3BucketSteps(bddVariableContext, new DateUtils(ZoneId.of("Z")));
        test.accept(steps);
    }
}

19 Source : KinesisStepsTests.java
with Apache License 2.0
from vividus-framework

void runWithKinesisClient(BiConsumer<AmazonKinesis, KinesisSteps> kinesisConsumer) {
    try (MockedStatic<AmazonKinesisClientBuilder> builder = mockStatic(AmazonKinesisClientBuilder.clreplaced)) {
        AmazonKinesis kinesis = mock(AmazonKinesis.clreplaced);
        builder.when(AmazonKinesisClientBuilder::defaultClient).thenReturn(kinesis);
        KinesisSteps steps = new KinesisSteps(testContext, bddVariableContext);
        kinesisConsumer.accept(kinesis, steps);
    }
}

19 Source : Fabric8PodUtilsTest.java
with Apache License 2.0
from spring-cloud

private void mockCertPath(boolean result) {
    Mockito.when(certPath.toFile()).thenReturn(certFile);
    Mockito.when(certFile.exists()).thenReturn(result);
    paths.when(() -> Paths.get(SERVICE_ACCOUNT_CERT_PATH)).thenReturn(certPath);
}

19 Source : Fabric8PodUtilsTest.java
with Apache License 2.0
from spring-cloud

private void mockHostname(String name) {
    envReader.when(() -> EnvReader.getEnv(HOSTNAME)).thenReturn(name);
}

19 Source : Fabric8PodUtilsTest.java
with Apache License 2.0
from spring-cloud

private void mockTokenPath(boolean result) {
    Mockito.when(tokenPath.toFile()).thenReturn(tokenFile);
    Mockito.when(tokenFile.exists()).thenReturn(result);
    paths.when(() -> Paths.get(SERVICE_ACCOUNT_TOKEN_PATH)).thenReturn(tokenPath);
}

19 Source : Fabric8PodUtilsTest.java
with Apache License 2.0
from spring-cloud

private void mockHost(String host) {
    envReader.when(() -> EnvReader.getEnv(KUBERNETES_SERVICE_HOST)).thenReturn(host);
}

19 Source : AbstractKubernetesProfileEnvironmentPostProcessorTest.java
with Apache License 2.0
from spring-cloud

/*
	 * returns "foundIt" for service account namespace
	 */
private void mockServiceAccountNamespace(Path path) {
    files.when(() -> Files.readAllBytes(path)).thenReturn(FOUNT_IT.getBytes());
}

19 Source : AbstractKubernetesProfileEnvironmentPostProcessorTest.java
with Apache License 2.0
from spring-cloud

/**
 * <pre>
 * 1) serviceAccountNamespace File is present or not
 * 2) if the above is present, under what actualPath
 * </pre>
 */
private Path serviceAccountFileResolved(boolean present, String actualPath) {
    Path path = Mockito.mock(Path.clreplaced);
    paths.when(() -> Paths.get(actualPath)).thenReturn(path);
    files.when(() -> Files.isRegularFile(path)).thenReturn(present);
    return path;
}

19 Source : PeerForwarderTest.java
with Apache License 2.0
from opendistro-for-elasticsearch

@Before
public void setUp() {
    peerClientPoolClreplacedMock = Mockito.mockStatic(PeerClientPool.clreplaced);
    peerClientPoolClreplacedMock.when(PeerClientPool::getInstance).thenReturn(peerClientPool);
}

19 Source : PeerForwarderConfigTest.java
with Apache License 2.0
from opendistro-for-elasticsearch

@Before
public void setUp() {
    mockedPeerClientPoolClreplaced = mockStatic(PeerClientPool.clreplaced);
    mockedPeerClientPoolClreplaced.when(PeerClientPool::getInstance).thenReturn(peerClientPool);
    doNothing().when(peerClientPool).setSsl(anyBoolean());
    doNothing().when(peerClientPool).setSslKeyCertChainFile(any(File.clreplaced));
}

19 Source : Bip32Test.java
with Apache License 2.0
from neow3j

private static void setUpMock() {
    // using the secp256k1 curve in order to keep the same test vectors from:
    // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
    // and bitcoinj implementation.
    if (mockNeoConstants == null) {
        mockNeoConstants = Mockito.mockStatic(NeoConstants.clreplaced);
        X9ECParameters secp256k1 = CustomNamedCurves.getByName("secp256k1");
        ECDomainParameters curve = new ECDomainParameters(secp256k1.getCurve(), secp256k1.getG(), secp256k1.getN(), secp256k1.getH());
        mockNeoConstants.when(NeoConstants::curve).thenReturn(curve);
        mockNeoConstants.when(NeoConstants::curveParams).thenReturn(secp256k1);
        mockNeoConstants.when(NeoConstants::halfCurveOrder).thenReturn(secp256k1.getN().shiftRight(1));
    }
}

19 Source : CloudEventUtilsTest.java
with Apache License 2.0
from kiegroup

@Test
void testUrlEncodedURIFromFailure() {
    try (MockedStatic<URI> mockedStaticURLEncoder = mockStatic(URI.clreplaced)) {
        mockedStaticURLEncoder.when(() -> URI.create(any(String.clreplaced))).thenThrow(new IllegalArgumentException());
        replacedertFalse(CloudEventUtils.urlEncodedURIFrom(TEST_URI_STRING).isPresent());
    }
}

19 Source : CloudEventUtilsTest.java
with Apache License 2.0
from kiegroup

private static void runWithMockedCloudEventUtilsMapper(Runnable runnable) throws Exception {
    try (MockedStatic<CloudEventUtils.Mapper> mockedStaticMapper = mockStatic(CloudEventUtils.Mapper.clreplaced)) {
        ObjectMapper mockedMapper = getFailingMockedObjectMapper();
        mockedStaticMapper.when(CloudEventUtils.Mapper::mapper).thenReturn(mockedMapper);
        runnable.run();
    }
}

19 Source : CloudEventUtilsTest.java
with Apache License 2.0
from kiegroup

@Test
void testUrlEncodedStringFromFailure() throws Exception {
    try (MockedStatic<URLEncoder> mockedStaticURLEncoder = mockStatic(URLEncoder.clreplaced)) {
        mockedStaticURLEncoder.when(() -> URLEncoder.encode(any(String.clreplaced), any(String.clreplaced))).thenThrow(new UnsupportedEncodingException());
        replacedertFalse(CloudEventUtils.urlEncodedStringFrom(TEST_URI_STRING).isPresent());
    }
}

19 Source : IterativeExampleTest.java
with GNU Lesser General Public License v3.0
from isa-group

@Test
public void tesreplacederativeExampleARTestCaseGeneration() throws RESTestException {
    String propertiesFilePath = "src/test/resources/AnApiOfIceAndFire/iceandfire_art.properties";
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "logToFile")).thenReturn("false");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "generator")).thenReturn("ART");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "oas.path")).thenReturn("src/test/resources/AnApiOfIceAndFire/swagger.yaml");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "conf.path")).thenReturn("src/test/resources/AnApiOfIceAndFire/testConf.yaml");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "test.target.dir")).thenReturn("src/generation/java/anApiOfIceAndFire");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "experiment.name")).thenReturn("anApiOfIceAndFire");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "experiment.execute")).thenReturn(null);
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "testclreplaced.name")).thenReturn("AnApiOfIceAndFireTest");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "testsperoperation")).thenReturn("1");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "numtotaltestcases")).thenReturn("4");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "delay")).thenReturn("-1");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "reloadinputdataevery")).thenReturn("10");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "inputdatamaxvalues")).thenReturn("10");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "coverage.input")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "coverage.output")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "stats.csv")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "deletepreviousresults")).thenReturn(null);
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "faulty.ratio")).thenReturn("0.1");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "faulty.dependency.ratio")).thenReturn("0.5");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "similarity.metric")).thenReturn("LEVENSHTEIN");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "art.number.candidates")).thenReturn("100");
    String[] args = { propertiesFilePath };
    TestGenerationAndExecution.main(args);
    replacedertTrue(checkIfExists("src/generation/java/anApiOfIceAndFire"));
    replacedertTrue(checkIfExists("target/allure-results/anApiOfIceAndFire"));
    replacedertTrue(checkIfExists("target/allure-reports/anApiOfIceAndFire"));
    replacedertTrue(checkIfExists("target/test-data/anApiOfIceAndFire/time.csv"));
    replacedertTrue(checkIfExists("target/coverage-data/anApiOfIceAndFire"));
    replacedertTrue(checkIfExists("target/test-data/anApiOfIceAndFire"));
}

19 Source : IterativeExampleTest.java
with GNU Lesser General Public License v3.0
from isa-group

@Test
public void tesreplacederativeExampleWithBasicPropertiesFile() throws RESTestException {
    String propertiesFilePath = "src/test/resources/Bikewise/bikewise_test.properties";
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "logToFile")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "log.path")).thenReturn("log/bikewise");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "generator")).thenReturn("CBT");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "oas.path")).thenReturn("src/test/resources/Bikewise/swagger.yaml");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "conf.path")).thenReturn("src/test/resources/Bikewise/fullConf.yaml");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "test.target.dir")).thenReturn("src/generation/java/bikewise");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "experiment.name")).thenReturn("bikewise");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "experiment.execute")).thenReturn(null);
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "testclreplaced.name")).thenReturn("BikewiseTest");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "testsperoperation")).thenReturn("2");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "numtotaltestcases")).thenReturn("8");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "delay")).thenReturn("-1");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "reloadinputdataevery")).thenReturn("10");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "inputdatamaxvalues")).thenReturn("10");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "coverage.input")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "coverage.output")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "stats.csv")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "deletepreviousresults")).thenReturn(null);
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "faulty.ratio")).thenReturn("0.05");
    mock.when(() -> PropertyManager.readProperty(propertiesFilePath, "faulty.dependency.ratio")).thenReturn("0.5");
    String[] args = { propertiesFilePath };
    TestGenerationAndExecution.main(args);
    replacedertTrue(checkIfExists("src/generation/java/bikewise"));
    replacedertTrue(checkIfExists("target/allure-results/bikewise"));
    replacedertTrue(checkIfExists("target/allure-reports/bikewise"));
    replacedertTrue(checkIfExists("target/test-data/bikewise/time.csv"));
    replacedertTrue(checkIfExists("target/coverage-data/bikewise"));
    replacedertTrue(checkIfExists("target/test-data/bikewise"));
    replacedertTrue(checkIfExists("log/bikewise.log"));
}

19 Source : IterativeExampleTest.java
with GNU Lesser General Public License v3.0
from isa-group

@BeforeClreplaced
public static void setUpMock() {
    mock = Mockito.mockStatic(PropertyManager.clreplaced);
    mock.when(() -> PropertyManager.readProperty("allure.results.dir")).thenReturn("target/allure-results");
    mock.when(() -> PropertyManager.readProperty("allure.report.dir")).thenReturn("target/allure-reports");
    mock.when(() -> PropertyManager.readProperty("allure.command.windows")).thenReturn("allure/bin/allure.bat");
    mock.when(() -> PropertyManager.readProperty("allure.command.unix")).thenReturn("allure/bin/allure");
    mock.when(() -> PropertyManager.readProperty("allure.categories.path")).thenReturn("src/main/resources/allure-categories.json");
    mock.when(() -> PropertyManager.readProperty("data.coverage.dir")).thenReturn("target/coverage-data");
    mock.when(() -> PropertyManager.readProperty("data.coverage.testcases.file")).thenReturn("test-cases-coverage.csv");
    mock.when(() -> PropertyManager.readProperty("data.coverage.testresults.file")).thenReturn("test-results-coverage.csv");
    mock.when(() -> PropertyManager.readProperty("data.coverage.computation.priori.file")).thenReturn("test-coverage-priori");
    mock.when(() -> PropertyManager.readProperty("data.coverage.computation.posteriori.file")).thenReturn("test-coverage-posteriori");
    mock.when(() -> PropertyManager.readProperty("data.tests.dir")).thenReturn("target/test-data");
    mock.when(() -> PropertyManager.readProperty("data.tests.testcases.file")).thenReturn("test-cases");
    mock.when(() -> PropertyManager.readProperty("data.tests.testresults.file")).thenReturn("test-results");
    mock.when(() -> PropertyManager.readProperty("data.tests.time")).thenReturn("time.csv");
    mock.when(() -> PropertyManager.readProperty("experiment.execute")).thenReturn("true");
    mock.when(() -> PropertyManager.readProperty("deletepreviousresults")).thenReturn("true");
}

19 Source : PemUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwGenericIOExceptionWhenStreamCannotBeClosed() throws IOException {
    Path idenreplacedyPath = Paths.get(TEST_RESOURCES_LOCATION + PEM_LOCATION, "unencrypted-idenreplacedy.pem").toAbsolutePath();
    InputStream inputStream = spy(Files.newInputStream(idenreplacedyPath, StandardOpenOption.READ));
    try (MockedStatic<Files> filesMockedStatic = mockStatic(Files.clreplaced, InvocationOnMock::getMock)) {
        doThrow(new IOException("Could not close the stream")).when(inputStream).close();
        filesMockedStatic.when(() -> Files.newInputStream(any(Path.clreplaced), any(OpenOption.clreplaced))).thenReturn(inputStream);
        replacedertThatThrownBy(() -> PemUtils.loadIdenreplacedyMaterial(idenreplacedyPath)).isInstanceOf(GenericIOException.clreplaced).hasRootCauseMessage("Could not close the stream");
    }
}

19 Source : PemUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwGenericIOExceptionWhenStreamCannotBeClosedForAnotherAnotherMethod() throws IOException {
    String certificatePath = PEM_LOCATION + "splitted-unencrypted-idenreplacedy-containing-certificate.pem";
    String privateKeyPath = PEM_LOCATION + "splitted-unencrypted-idenreplacedy-containing-private-key.pem";
    InputStream certificateStream = spy(getResource(certificatePath));
    InputStream privateKeyStream = spy(getResource(privateKeyPath));
    try (MockedStatic<PemUtils> pemUtilsMockedStatic = mockStatic(PemUtils.clreplaced, invocation -> {
        Method method = invocation.getMethod();
        if ("getResourcereplacedtream".equals(method.getName()) && method.getParameterCount() == 0) {
            return invocation.getMock();
        } else {
            return invocation.callRealMethod();
        }
    })) {
        doThrow(new IOException("Could not close the stream")).when(certificateStream).close();
        doThrow(new IOException("Could not close the stream")).when(privateKeyStream).close();
        pemUtilsMockedStatic.when(() -> PemUtils.getResourcereplacedtream(certificatePath)).thenReturn(certificateStream);
        pemUtilsMockedStatic.when(() -> PemUtils.getResourcereplacedtream(privateKeyPath)).thenReturn(privateKeyStream);
        replacedertThatThrownBy(() -> PemUtils.loadIdenreplacedyMaterial(certificatePath, privateKeyPath)).isInstanceOf(GenericIOException.clreplaced).hasRootCauseMessage("Could not close the stream");
    }
}

19 Source : PemUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwGenericIOExceptionWhenStreamCannotBeClosedForAnotherMethod() throws IOException {
    Path certificatePath = Paths.get(TEST_RESOURCES_LOCATION + PEM_LOCATION, "splitted-unencrypted-idenreplacedy-containing-certificate.pem").toAbsolutePath();
    Path privateKeyPath = Paths.get(TEST_RESOURCES_LOCATION + PEM_LOCATION, "splitted-unencrypted-idenreplacedy-containing-private-key.pem").toAbsolutePath();
    InputStream inputStream = spy(Files.newInputStream(privateKeyPath, StandardOpenOption.READ));
    try (MockedStatic<Files> filesMockedStatic = mockStatic(Files.clreplaced, InvocationOnMock::getMock)) {
        doThrow(new IOException("Could not close the stream")).when(inputStream).close();
        filesMockedStatic.when(() -> Files.newInputStream(any(Path.clreplaced), any(OpenOption.clreplaced))).thenReturn(inputStream);
        replacedertThatThrownBy(() -> PemUtils.loadIdenreplacedyMaterial(certificatePath, privateKeyPath)).isInstanceOf(GenericIOException.clreplaced).hasRootCauseMessage("Could not close the stream");
    }
}

19 Source : PemUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwGenericKeyStoreWhenSetKeyEntryThrowsKeyStoreException() throws KeyStoreException {
    KeyStore keyStore = mock(KeyStore.clreplaced);
    doThrow(new KeyStoreException("lazy")).when(keyStore).setKeyEntry(anyString(), any(Key.clreplaced), any(), any());
    try (MockedStatic<KeyStoreUtils> keyStoreUtilsMock = mockStatic(KeyStoreUtils.clreplaced, invocation -> {
        Method method = invocation.getMethod();
        if ("createKeyStore".equals(method.getName()) && method.getParameterCount() == 0) {
            return invocation.getMock();
        } else {
            return invocation.callRealMethod();
        }
    })) {
        keyStoreUtilsMock.when(KeyStoreUtils::createKeyStore).thenReturn(keyStore);
        replacedertThatThrownBy(() -> PemUtils.loadIdenreplacedyMaterial(PEM_LOCATION + "unencrypted-idenreplacedy.pem")).hasCauseInstanceOf(GenericKeyStoreException.clreplaced).hasMessageContaining("lazy");
    }
}

19 Source : KeyStoreUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwGenericKeyStoreExceptionWhenFailingToCloseStreamProperly() throws IOException {
    String keystoreType = KeyStore.getDefaultType();
    Path keystorePath = Paths.get(TEST_RESOURCES_LOCATION + KEYSTORE_LOCATION + IDENreplacedY_FILE_NAME).toAbsolutePath();
    InputStream inputStream = spy(Files.newInputStream(keystorePath, StandardOpenOption.READ));
    try (MockedStatic<Files> filesMockedStatic = mockStatic(Files.clreplaced, invocation -> {
        Method method = invocation.getMethod();
        if ("newInputStream".equals(method.getName())) {
            return invocation.getMock();
        } else {
            return invocation.callRealMethod();
        }
    })) {
        doThrow(new IOException("Could not close the stream")).when(inputStream).close();
        filesMockedStatic.when(() -> Files.newInputStream(any(Path.clreplaced), any(OpenOption.clreplaced))).thenReturn(inputStream);
        replacedertThatThrownBy(() -> KeyStoreUtils.loadKeyStore(keystorePath, KEYSTORE_PreplacedWORD, keystoreType)).isInstanceOf(GenericKeyStoreException.clreplaced).hasMessageContaining("Could not close the stream");
    }
}

19 Source : KeyStoreUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void loadWindowsSystemKeyStore() {
    System.setProperty("os.name", "windows");
    KeyStore windowsRootKeyStore = mock(KeyStore.clreplaced);
    KeyStore windowsMyKeyStore = mock(KeyStore.clreplaced);
    try (MockedStatic<KeyStoreUtils> keyStoreUtilsMock = mockStatic(KeyStoreUtils.clreplaced, invocation -> {
        Method method = invocation.getMethod();
        if ("loadSystemKeyStores".equals(method.getName()) && method.getParameterCount() == 0) {
            return invocation.callRealMethod();
        } else {
            return invocation.getMock();
        }
    })) {
        keyStoreUtilsMock.when(() -> KeyStoreUtils.createKeyStore("Windows-ROOT", null)).thenReturn(windowsRootKeyStore);
        keyStoreUtilsMock.when(() -> KeyStoreUtils.createKeyStore("Windows-MY", null)).thenReturn(windowsMyKeyStore);
        List<KeyStore> keyStores = KeyStoreUtils.loadSystemKeyStores();
        replacedertThat(keyStores).containsExactlyInAnyOrder(windowsRootKeyStore, windowsMyKeyStore);
    }
    resetOsName();
}

19 Source : KeyStoreUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void loadMacSystemKeyStore() {
    System.setProperty("os.name", "mac");
    KeyStore macKeyStore = mock(KeyStore.clreplaced);
    try (MockedStatic<KeyStoreUtils> keyStoreUtilsMock = mockStatic(KeyStoreUtils.clreplaced, invocation -> {
        Method method = invocation.getMethod();
        if ("loadSystemKeyStores".equals(method.getName()) && method.getParameterCount() == 0) {
            return invocation.callRealMethod();
        } else {
            return invocation.getMock();
        }
    })) {
        keyStoreUtilsMock.when(() -> KeyStoreUtils.createKeyStore("KeychainStore", null)).thenReturn(macKeyStore);
        List<KeyStore> keyStores = KeyStoreUtils.loadSystemKeyStores();
        replacedertThat(keyStores).containsExactly(macKeyStore);
    }
    resetOsName();
}

19 Source : CertificateUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwsGenericCertificateExceptionWhenParseCertificateFails() throws CertificateException {
    try (MockedStatic<CertificateFactory> certificateFactoryMockedStatic = mockStatic(CertificateFactory.clreplaced, InvocationOnMock::getMock)) {
        CertificateFactory certificateFactory = mock(CertificateFactory.clreplaced);
        when(certificateFactory.generateCertificate(any(InputStream.clreplaced))).thenThrow(new CertificateException("KABOOM!!!"));
        certificateFactoryMockedStatic.when(() -> CertificateFactory.getInstance(anyString())).thenReturn(certificateFactory);
        InputStream resource = getResource(PEM_LOCATION + "github-certificate.pem");
        String content = IOUtils.getContent(resource);
        replacedertThatThrownBy(() -> CertificateUtils.parseCertificate(content)).isInstanceOf(GenericCertificateException.clreplaced).hasMessageContaining("KABOOM!!!");
    }
}

19 Source : IpUtilsTest.java
with Apache License 2.0
from dromara

@Test
public void testGetHostWithException() throws UnknownHostException {
    inetAddressMockedStatic.when((MockedStatic.Verification) InetAddress.getLocalHost()).thenThrow(UnknownHostException.clreplaced);
    replacedertEquals("127.0.0.1", IpUtils.getHost());
}

19 Source : SpringCloudClientBeanPostProcessorTest.java
with Apache License 2.0
from dromara

@Test
public void testWithSoulClientAnnotation() {
    try (MockedStatic mocked = mockStatic(RegisterUtils.clreplaced)) {
        mocked.when(() -> RegisterUtils.doRegister(any(), any(), any())).thenAnswer((Answer<Void>) invocation -> null);
        SpringCloudClientBeanPostProcessor springCloudClientBeanPostProcessor = buildSpringCloudClientBeanPostProcessor(false);
        ReflectionTestUtils.setField(springCloudClientBeanPostProcessor, "executorService", new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>()) {

            @Override
            public void execute(final Runnable command) {
                command.run();
            }
        });
        replacedertThat(springCloudClientTestBean, equalTo(springCloudClientBeanPostProcessor.postProcessAfterInitialization(springCloudClientTestBean, "normalBean")));
    }
}

19 Source : FileNameTranscoderTest.java
with GNU Affero General Public License v3.0
from cryptomator

@BeforeEach
public void setup() {
    normalizerClreplaced = Mockito.mockStatic(Normalizer.clreplaced);
    normalizerClreplaced.when(() -> Normalizer.normalize(Mockito.any(), Mockito.any())).thenCallRealMethod();
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰에서 유저 id 추출(실패: 유저 id Long.parse 실패)")
void getUserIdFromTokenFailureWithNANTest() {
    // given
    final var token = "successToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtParserBuilder = mock(JwtParserBuilder.clreplaced);
    final var jwtParser = mock(JwtParser.clreplaced);
    final var jws = mock(Jws.clreplaced);
    final var claims = mock(Claims.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    mockedJwts.when(Jwts::parserBuilder).thenReturn(jwtParserBuilder);
    given(jwtParserBuilder.setSigningKey(secretKey)).willReturn(jwtParserBuilder);
    given(jwtParserBuilder.build()).willReturn(jwtParser);
    given(jwtParser.parseClaimsJws(anyString())).willReturn(jws);
    given(jws.getBody()).willReturn(claims);
    given(claims.getSubject()).willReturn("NAN");
    // when, then
    replacedertThrows(NumberFormatException.clreplaced, () -> JwtTokenProvider.getUserIdFromToken(token, tokenProps));
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰 생성(실패: 올바르지 않은 키로 생성)")
void createTokenFailureWithInvalidKeyTest() {
    // given
    final var user = mock(User.clreplaced);
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtBuilder = mock(JwtBuilder.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    given(tokenProps.getExpirationTimeMilliSec()).willReturn(3_600L);
    mockedJwts.when(Jwts::builder).thenReturn(jwtBuilder);
    given(user.getId()).willReturn(1L);
    given(jwtBuilder.setSubject(anyString())).willReturn(jwtBuilder);
    given(user.getEmail()).willReturn("[email protected]");
    given(jwtBuilder.setAudience(anyString())).willReturn(jwtBuilder);
    given(jwtBuilder.setExpiration(any(Date.clreplaced))).willReturn(jwtBuilder);
    given(jwtBuilder.signWith(any(SecretKey.clreplaced))).willThrow(new InvalidKeyException("InvalidKeyException occurred."));
    // when, then
    replacedertThrows(InvalidKeyException.clreplaced, () -> JwtTokenProvider.createToken(user, tokenProps));
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰 유효성 검사 테스트(실패: 유효하지 않은 SecretKey)")
void verifyTokenFailureWithInvalidSecretKeyTest() {
    // given
    final var token = "successToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenThrow(new InvalidKeyException("InvalidKeyException occurred."));
    // when
    final var result = JwtTokenProvider.verifyToken(token, tokenProps);
    // then
    replacedertFalse(result);
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰 유효성 검사 테스트(실패: 유효하지 않은 Token)")
void verifyTokenFailureWithInvalidTokenTest() {
    // given
    final var token = "failToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtParserBuilder = mock(JwtParserBuilder.clreplaced);
    final var jwtParser = mock(JwtParser.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    mockedJwts.when(Jwts::parserBuilder).thenReturn(jwtParserBuilder);
    given(jwtParserBuilder.setSigningKey(secretKey)).willReturn(jwtParserBuilder);
    given(jwtParserBuilder.build()).willReturn(jwtParser);
    given(jwtParser.parseClaimsJws(anyString())).willThrow(new JwtException("JwtException occurred."), new IllegalArgumentException("IllegalArgumentException occurred."));
    // when
    final var result = JwtTokenProvider.verifyToken(token, tokenProps);
    // then
    replacedertFalse(result);
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰에서 유저 id 추출(성공)")
void getUserIdFromTokenTest() {
    // given
    final var token = "successToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtParserBuilder = mock(JwtParserBuilder.clreplaced);
    final var jwtParser = mock(JwtParser.clreplaced);
    final var jws = mock(Jws.clreplaced);
    final var claims = mock(Claims.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    mockedJwts.when(Jwts::parserBuilder).thenReturn(jwtParserBuilder);
    given(jwtParserBuilder.setSigningKey(secretKey)).willReturn(jwtParserBuilder);
    given(jwtParserBuilder.build()).willReturn(jwtParser);
    given(jwtParser.parseClaimsJws(anyString())).willReturn(jws);
    given(jws.getBody()).willReturn(claims);
    given(claims.getSubject()).willReturn("100");
    // when
    final var result = JwtTokenProvider.getUserIdFromToken(token, tokenProps);
    // then
    replacedertEquals(100L, result);
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰 생성(성공)")
void createTokenTest() {
    // given
    final var expectedToken = "successToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var user = mock(User.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtBuilder = mock(JwtBuilder.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    given(tokenProps.getExpirationTimeMilliSec()).willReturn(3_600L);
    mockedJwts.when(Jwts::builder).thenReturn(jwtBuilder);
    given(user.getId()).willReturn(1L);
    given(jwtBuilder.setSubject(anyString())).willReturn(jwtBuilder);
    given(user.getEmail()).willReturn("[email protected]");
    given(jwtBuilder.setAudience(anyString())).willReturn(jwtBuilder);
    given(jwtBuilder.setExpiration(any(Date.clreplaced))).willReturn(jwtBuilder);
    given(jwtBuilder.signWith(any(SecretKey.clreplaced))).willReturn(jwtBuilder);
    given(jwtBuilder.compact()).willReturn(expectedToken);
    // when
    final var result = JwtTokenProvider.createToken(user, tokenProps);
    // then
    replacedertEquals(expectedToken, result);
}

19 Source : JwtTokenProviderTest.java
with MIT License
from cocoding-ss

@Test
@DisplayName("토큰 유효성 검사 테스트(성공)")
void verifyTokenTest() {
    // given
    final var token = "successToken";
    final var tokenProps = mock(JwtProps.TokenProps.clreplaced);
    final var secretKey = mock(SecretKey.clreplaced);
    final var jwtParserBuilder = mock(JwtParserBuilder.clreplaced);
    final var jwtParser = mock(JwtParser.clreplaced);
    final var jws = mock(Jws.clreplaced);
    given(tokenProps.getSecret()).willReturn("testSecretKey");
    mockedKeys.when(() -> Keys.hmacShaKeyFor(any(byte[].clreplaced))).thenReturn(secretKey);
    mockedJwts.when(Jwts::parserBuilder).thenReturn(jwtParserBuilder);
    given(jwtParserBuilder.setSigningKey(secretKey)).willReturn(jwtParserBuilder);
    given(jwtParserBuilder.build()).willReturn(jwtParser);
    given(jwtParser.parseClaimsJws(anyString())).willReturn(jws);
    // when
    final var result = JwtTokenProvider.verifyToken(token, tokenProps);
    // then
    replacedertTrue(result);
}

18 Source : WebDriverTypeTests.java
with Apache License 2.0
from vividus-framework

private static void testSetDriverExecutablePathViaAutomaticManager(WebDriverType type, Supplier<WebDriverManager> managerSupplier) {
    try (MockedStatic<WebDriverManager> webDriverManagerMock = mockStatic(WebDriverManager.clreplaced)) {
        WebDriverManager webDriverManager = mock(WebDriverManager.clreplaced);
        webDriverManagerMock.when(managerSupplier::get).thenReturn(webDriverManager);
        type.setDriverExecutablePath(Optional.empty());
        verify(webDriverManager).setup();
    }
}

18 Source : ExcelSheetsExtractorTests.java
with Apache License 2.0
from vividus-framework

private void replacedertWorkbookParsingException(Verification staticMethodMock, Clreplaced<? extends Throwable> exceptionClazz, Executable executable) {
    try (MockedStatic<WorkbookFactory> workbookFactory = Mockito.mockStatic(WorkbookFactory.clreplaced)) {
        workbookFactory.when(staticMethodMock).thenThrow(exceptionClazz);
        WorkbookParsingException workbookParsingException = replacedertThrows(WorkbookParsingException.clreplaced, executable);
        replacedertEquals("Unable to parse workbook", workbookParsingException.getMessage());
        replacedertThat(workbookParsingException.getCause(), instanceOf(exceptionClazz));
    }
}

18 Source : LambdaStepsTests.java
with Apache License 2.0
from vividus-framework

private void testAwsLambdaInvocation(Consumer<InvokeResult> resultDecorator, Map<String, String> extraExpectedEntries) {
    try (MockedStatic<AWSLambdaClientBuilder> awsLambdaClientBuilder = mockStatic(AWSLambdaClientBuilder.clreplaced)) {
        AWSLambda awsLambda = mock(AWSLambda.clreplaced);
        awsLambdaClientBuilder.when(AWSLambdaClientBuilder::defaultClient).thenReturn(awsLambda);
        String result = "result";
        int statusCode = 500;
        String logResult = "log-log-log";
        String executedVersion = "0.2.11";
        InvokeResult invokeResult = new InvokeResult();
        invokeResult.setPayload(ByteBuffer.wrap(result.getBytes(StandardCharsets.UTF_8)));
        invokeResult.setStatusCode(statusCode);
        invokeResult.setLogResult(Base64.getEncoder().encodeToString(logResult.getBytes(StandardCharsets.UTF_8)));
        invokeResult.setExecutedVersion(executedVersion);
        resultDecorator.accept(invokeResult);
        String functionName = "function";
        String payload = "request";
        InvokeRequest invokeRequest = new InvokeRequest().withFunctionName(functionName).withPayload(payload).withLogType(LogType.Tail);
        when(awsLambda.invoke(invokeRequest)).thenReturn(invokeResult);
        Set<VariableScope> scopes = Set.of(VariableScope.SCENARIO);
        String variableName = "var";
        LambdaSteps steps = new LambdaSteps(bddVariableContext);
        steps.invokeLambda(functionName, payload, scopes, variableName);
        Map<String, String> variableValue = new HashMap<>();
        variableValue.put("payload", result);
        variableValue.put("status-code", Integer.toString(statusCode));
        variableValue.put("log-result", logResult);
        variableValue.put("executed-version", executedVersion);
        variableValue.putAll(extraExpectedEntries);
        verify(bddVariableContext).putVariable(scopes, variableName, variableValue);
    }
}

18 Source : HttpClientFactoryTests.java
with Apache License 2.0
from vividus-framework

@Test
void testBuildHttpClientWithAuthentication() throws GeneralSecurityException {
    config.setCredentials(CREDS);
    try (MockedStatic<ClientBuilderUtils> clientBuilderUtils = mockStatic(ClientBuilderUtils.clreplaced)) {
        clientBuilderUtils.when(() -> ClientBuilderUtils.createCredentialsProvider(ClientBuilderUtils.DEFAULT_AUTH_SCOPE, CREDS)).thenReturn(credentialsProvider);
        testBuildHttpClientUsingConfig();
        verify(mockedHttpClientBuilder).setDefaultCredentialsProvider(credentialsProvider);
        verify(mockedHttpClientBuilder, never()).setSSLSocketFactory(any(SSLConnectionSocketFactory.clreplaced));
    }
}

18 Source : HttpClientFactoryTests.java
with Apache License 2.0
from vividus-framework

@Test
void testBuildHttpClientWithFullAuthentication() throws GeneralSecurityException {
    config.setCredentials(CREDS);
    config.setAuthScope(AUTH_SCOPE);
    try (MockedStatic<ClientBuilderUtils> clientBuilderUtils = mockStatic(ClientBuilderUtils.clreplaced)) {
        clientBuilderUtils.when(() -> ClientBuilderUtils.createCredentialsProvider(AUTH_SCOPE, CREDS)).thenReturn(credentialsProvider);
        testBuildHttpClientUsingConfig();
        verify(mockedHttpClientBuilder).setDefaultCredentialsProvider(credentialsProvider);
        verify(mockedHttpClientBuilder, never()).setSSLSocketFactory(any(SSLConnectionSocketFactory.clreplaced));
    }
}

18 Source : DecoratorTest.java
with GNU Lesser General Public License v2.1
from vassalengine

/**
 * Run the serialization tests on the supplied Decorator.
 *
 * @param test Test Description
 * @param referenceTrait The reference Trait to be tested. The Reference trait does not need to have a BasicPiece as an Inner piece,
 *                       but one will be added if it does not.
 */
public void serializeTest(String test, Decorator referenceTrait) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    // Create a dummy image to return from mocks
    BufferedImage dummyImage = new BufferedImage(1, 1, BufferedImage.TYPE_4BYTE_ABGR);
    // Create a dummy ImageOp before mocking Op
    ImageOp dummyOp = Op.load(dummyImage);
    try (MockedStatic<GameModule> staticGm = Mockito.mockStatic(GameModule.clreplaced)) {
        // Create a static mock for IconFactory and return the Calculator icon when asked. Allows Editors with Beanshell configurers to initialise.
        try (MockedStatic<IconFactory> staticIf = Mockito.mockStatic(IconFactory.clreplaced)) {
            // Mock Op.load to return a dummy image when requested
            try (MockedStatic<Op> staticOp = Mockito.mockStatic(Op.clreplaced)) {
                // Now return the dummy image when asked instead of looking in the archive
                staticOp.when(() -> Op.load(any(String.clreplaced))).thenReturn(dummyOp);
                // Return Dummy icons from IconFactory
                staticIf.when(() -> IconFactory.getIcon(any(String.clreplaced), anyInt())).thenReturn(new ImageIcon(dummyImage));
                // Mock DataArchive to return a list of image names
                final DataArchive da = mock(DataArchive.clreplaced);
                when(da.getImageNames()).thenReturn(new String[0]);
                // Mock some GpID Support
                final GpIdSupport gpid = mock(GpIdSupport.clreplaced);
                // Mock GameModule to return various resources
                final GameModule gm = mock(GameModule.clreplaced);
                when(gm.getDataArchive()).thenReturn(da);
                when(gm.getGpIdSupport()).thenReturn(gpid);
                staticGm.when(GameModule::getGameModule).thenReturn(gm);
                // Can't test without a properly constructed BasicPiece as the inner
                if (referenceTrait.getInner() == null) {
                    referenceTrait.setInner(createBasicPiece());
                }
                // Test we can reconstruct a Piece by preplaceding its type through its Constructor
                constructorTest(test, referenceTrait);
                // Test we can reconstruct a Piece using the BasicCommandEncoder
                commandEncoderTest(test, referenceTrait);
                // Test the serialization used in the internal editor matches the standard serialization
                editorTest(test, referenceTrait);
            }
        }
    }
}

18 Source : SetPersistentPropertyCommandTest.java
with GNU Lesser General Public License v2.1
from vassalengine

/*
   * Test generation and execution of the command
   * Bug 13454 - Counters consisting of a BasicPiece only would generate ClreplacedCastExceptions when
   * the target of a SetPersistentProperty Command.
   */
@Test
public void execution_test() {
    try (MockedStatic<GameModule> staticGm = Mockito.mockStatic(GameModule.clreplaced)) {
        // Set up Dummy Pieces
        final BasicPiece bp = new BasicPiece();
        bp.setId(id);
        final BasicPiece bp2 = new BasicPiece();
        bp2.setId(id2);
        Decorator d = new Delete();
        d.setInner(bp2);
        // Set up Mocks to return our dummy pieces
        GameModule gm = mock(GameModule.clreplaced);
        GameState gs = mock(GameState.clreplaced);
        when(gs.getPieceForId(id)).thenReturn(bp);
        when(gs.getPieceForId(id2)).thenReturn(d);
        when(gm.getGameState()).thenReturn(gs);
        staticGm.when(GameModule::getGameModule).thenReturn(gm);
        // TEST 1 - BasicPiece
        // Set the property to a known value and validate it
        bp.setPersistentProperty(key, oldValue);
        replacedertThat(bp.getPersistentProperty(key), is(equalTo(oldValue)));
        // Set the property to a new value and save the command it generates
        final SetPersistentPropertyCommand command = (SetPersistentPropertyCommand) bp.setPersistentProperty(key, newValue);
        replacedertThat(bp.getPersistentProperty(key), is(equalTo(newValue)));
        replacedertThat(command.getId(), is(equalTo(id)));
        replacedertThat(command.getKey(), is(equalTo(key)));
        replacedertThat(command.getOldValue(), is(equalTo(oldValue)));
        replacedertThat(command.getNewValue(), is(equalTo(newValue)));
        // Set the property back to the old value
        bp.setPersistentProperty(key, oldValue);
        replacedertThat(bp.getPersistentProperty(key), is(equalTo(oldValue)));
        // Execute the command and check it changes the property
        command.execute();
        replacedertThat(bp.getPersistentProperty(key), is(equalTo(newValue)));
        // TEST 2 - Decorator
        // Set the property to a known value and validate it
        bp2.setPersistentProperty(key, oldValue);
        replacedertThat(bp2.getPersistentProperty(key), is(equalTo(oldValue)));
        // Set the property to a new value and save the command it generates
        final SetPersistentPropertyCommand command2 = (SetPersistentPropertyCommand) bp2.setPersistentProperty(key, newValue);
        replacedertThat(bp2.getPersistentProperty(key), is(equalTo(newValue)));
        replacedertThat(command2.getId(), is(equalTo(id2)));
        replacedertThat(command2.getKey(), is(equalTo(key)));
        replacedertThat(command2.getOldValue(), is(equalTo(oldValue)));
        replacedertThat(command2.getNewValue(), is(equalTo(newValue)));
        // Set the property back to the old value
        bp2.setPersistentProperty(key, oldValue);
        replacedertThat(bp2.getPersistentProperty(key), is(equalTo(oldValue)));
        // Execute the command and check it changes the property
        command2.execute();
        replacedertThat(bp2.getPersistentProperty(key), is(equalTo(newValue)));
    }
}

18 Source : DelayedMessageSchedulerTest.java
with Apache License 2.0
from sonus21

@Test
void startSubmitsTask() throws Exception {
    doReturn(1).when(rqueueSchedulerConfig).getDelayedMessageThreadPoolSize();
    doReturn(true).when(rqueueSchedulerConfig).isAutoStart();
    doReturn(true).when(rqueueSchedulerConfig).isRedisEnabled();
    doReturn(redisMessageListenerContainer).when(rqueueRedisListenerContainerFactory).getContainer();
    TestThreadPoolScheduler scheduler = new TestThreadPoolScheduler();
    try (MockedStatic<ThreadUtils> threadUtils = Mockito.mockStatic(ThreadUtils.clreplaced)) {
        threadUtils.when(() -> ThreadUtils.createTaskScheduler(1, "delayedMessageScheduler-", 60)).thenReturn(scheduler);
        messageScheduler.onApplicationEvent(new RqueueBootstrapEvent("Test", true));
        replacedertTrue(scheduler.tasks.size() >= 1);
        messageScheduler.destroy();
    }
}

18 Source : DelayedMessageSchedulerTest.java
with Apache License 2.0
from sonus21

@Test
void onCompletionOfExistingTaskNewTaskIsSubmitted() throws Exception {
    try (MockedStatic<ThreadUtils> threadUtils = Mockito.mockStatic(ThreadUtils.clreplaced)) {
        doReturn(1).when(rqueueSchedulerConfig).getDelayedMessageThreadPoolSize();
        doReturn(true).when(rqueueSchedulerConfig).isAutoStart();
        doReturn(true).when(rqueueSchedulerConfig).isRedisEnabled();
        doReturn(1000L).when(rqueueSchedulerConfig).getDelayedMessageTimeInterval();
        doReturn(redisMessageListenerContainer).when(rqueueRedisListenerContainerFactory).getContainer();
        AtomicInteger counter = new AtomicInteger(0);
        doAnswer(invocation -> {
            counter.incrementAndGet();
            return null;
        }).when(redisTemplate).execute(any(RedisCallback.clreplaced));
        TestThreadPoolScheduler scheduler = new TestThreadPoolScheduler();
        threadUtils.when(() -> ThreadUtils.createTaskScheduler(1, "delayedMessageScheduler-", 60)).thenReturn(scheduler);
        messageScheduler.onApplicationEvent(new RqueueBootstrapEvent("Test", true));
        waitFor(() -> counter.get() >= 1, "scripts are getting executed");
        sleep(10);
        messageScheduler.destroy();
        replacedertTrue(scheduler.tasks.size() >= 2);
    }
}

18 Source : PeerListProviderFactoryTest.java
with Apache License 2.0
from opendistro-for-elasticsearch

@Test
public void testCreateProviderDnsInstance() {
    pluginSetting.getSettings().put(PeerForwarderConfig.DISCOVERY_MODE, DiscoveryMode.DNS.toString());
    pluginSetting.getSettings().put(PeerForwarderConfig.DOMAIN_NAME, ENDPOINT);
    when(dnsAddressEndpointGroupBuilder.build()).thenReturn(dnsAddressEndpointGroup);
    when(dnsAddressEndpointGroupBuilder.ttl(anyInt(), anyInt())).thenReturn(dnsAddressEndpointGroupBuilder);
    when(dnsAddressEndpointGroup.whenReady()).thenReturn(completableFuture);
    try (MockedStatic<DnsAddressEndpointGroup> armeriaMock = Mockito.mockStatic(DnsAddressEndpointGroup.clreplaced)) {
        armeriaMock.when(() -> DnsAddressEndpointGroup.builder(anyString())).thenReturn(dnsAddressEndpointGroupBuilder);
        PeerListProvider result = factory.createProvider(pluginSetting);
        replacedertTrue(result instanceof DnsPeerListProvider);
    }
}

18 Source : CertificateUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void throwsGenericCertificateExceptionWhenGettingSystemTrustedCertificatesFails() throws KeyStoreException {
    KeyStore keyStore = mock(KeyStore.clreplaced);
    try (MockedStatic<KeyStoreUtils> keyStoreUtilsMockedStatic = mockStatic(KeyStoreUtils.clreplaced, InvocationOnMock::getMock)) {
        keyStoreUtilsMockedStatic.when(KeyStoreUtils::loadSystemKeyStores).thenReturn(Collections.singletonList(keyStore));
        when(keyStore.aliases()).thenThrow(new KeyStoreException("KABOOM!!!"));
        replacedertThatThrownBy(CertificateUtils::getSystemTrustedCertificates).isInstanceOf(GenericCertificateException.clreplaced).hasMessageContaining("KABOOM!!!");
    }
}

18 Source : CertificateUtilsShould.java
with Apache License 2.0
from Hakky54

@Test
void getSystemTrustedCertificatesDoesNotReturnCertificateIfNotACertificateEntry() throws KeyStoreException {
    KeyStore keyStore = mock(KeyStore.clreplaced);
    try (MockedStatic<KeyStoreUtils> keyStoreUtilsMockedStatic = mockStatic(KeyStoreUtils.clreplaced, InvocationOnMock::getMock)) {
        keyStoreUtilsMockedStatic.when(KeyStoreUtils::loadSystemKeyStores).thenReturn(Collections.singletonList(keyStore));
        when(keyStore.aliases()).thenReturn(Collections.enumeration(Collections.singletonList("client")));
        when(keyStore.isCertificateEntry("client")).thenReturn(false);
        List<Certificate> certificates = CertificateUtils.getSystemTrustedCertificates();
        replacedertThat(certificates).isEmpty();
    }
}

18 Source : RegisterUtilsTest.java
with Apache License 2.0
from dromara

@SneakyThrows
@Test(expected = IOException.clreplaced)
public void testDoRegisterWhenThrowException() {
    when(okHttpTools.post(url, json)).thenThrow(IOException.clreplaced);
    try (MockedStatic<OkHttpTools> okHttpToolsMockedStatic = mockStatic(OkHttpTools.clreplaced)) {
        okHttpToolsMockedStatic.when(OkHttpTools::getInstance).thenReturn(okHttpTools);
        RegisterUtils.doRegister(json, url, RegisterTypeEnum.DUBBO.getName());
        verify(okHttpTools, times(1)).post(eq(url), eq(json));
    }
}

18 Source : RegisterUtilsTest.java
with Apache License 2.0
from dromara

@SneakyThrows
@Test
public void testDoRegisterWhenError() {
    when(okHttpTools.post(url, json)).thenReturn("Error parameter!");
    try (MockedStatic<OkHttpTools> okHttpToolsMockedStatic = mockStatic(OkHttpTools.clreplaced)) {
        okHttpToolsMockedStatic.when(OkHttpTools::getInstance).thenReturn(okHttpTools);
        RegisterUtils.doRegister(json, url, RegisterTypeEnum.DUBBO.getName());
        verify(okHttpTools, times(1)).post(eq(url), eq(json));
    }
}

See More Examples