All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.dropwizard.testing.common.DropwizardClient Maven / Gradle / Ivy

There is a newer version: 5.0.0-alpha.2
Show newest version
package io.dropwizard.testing.common;

import com.codahale.metrics.health.HealthCheck;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.dropwizard.core.Application;
import io.dropwizard.core.Configuration;
import io.dropwizard.core.server.SimpleServerFactory;
import io.dropwizard.core.setup.Environment;
import io.dropwizard.jetty.HttpConnectorFactory;
import io.dropwizard.testing.DropwizardTestSupport;

import java.net.URI;

public class DropwizardClient {
    private final Object[] resources;
    private final DropwizardTestSupport testSupport;

    public DropwizardClient(Object... resources) {
        testSupport = new DropwizardTestSupport(FakeApplication.class, "") {
            @Override
            public Application newApplication() {
                return new FakeApplication();
            }
        };
        this.resources = resources;
    }

    public URI baseUri() {
        return URI.create("http://localhost:" + testSupport.getLocalPort() + "/application");
    }

    public ObjectMapper getObjectMapper() {
        return testSupport.getObjectMapper();
    }

    public Environment getEnvironment() {
        return testSupport.getEnvironment();
    }

    public void before() throws Throwable {
        testSupport.before();
    }

    public void after() {
        testSupport.after();
    }

    private static class DummyHealthCheck extends HealthCheck {
        @Override
        protected Result check() {
            return Result.healthy();
        }
    }

    private class FakeApplication extends Application {
        @Override
        public void run(Configuration configuration, Environment environment) {
            final SimpleServerFactory serverConfig = new SimpleServerFactory();
            configuration.setServerFactory(serverConfig);
            final HttpConnectorFactory connectorConfig = (HttpConnectorFactory) serverConfig.getConnector();
            connectorConfig.setPort(0);

            environment.healthChecks().register("dummy", new DummyHealthCheck());

            for (Object resource : resources) {
                if (resource instanceof Class) {
                    environment.jersey().register((Class) resource);
                } else {
                    environment.jersey().register(resource);
                }
            }
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy