Reputation: 3447
I'm looking to test the Dropwizard 'Application' class without bootstrapping an entire Dropwizard server.
I'd essentially just like to ensure that the one bundle I'm registering is registered successfully.
All the routes I've been down so far result in NullPointer exceptions due to various other components not being setup correctly. Is there an easy path here?
public class SentimentApplication extends Application<SentimentConfiguration> {
public static void main(final String[] args) throws Exception {
new SentimentApplication().run(args);
}
@Override
public String getName() {
return "Sentiment";
}
@Override
public void initialize(final Bootstrap<SentimentConfiguration> bootstrap) {
bootstrap.setConfigurationSourceProvider(
new SubstitutingSourceProvider(bootstrap.getConfigurationSourceProvider(),
new EnvironmentVariableSubstitutor(false)
)
);
}
@Override
public void run(final SentimentConfiguration configuration,
final Environment environment) {
// TODO: implement application
}
}
Upvotes: 3
Views: 1408
Reputation: 174
You can register a simple command and call run
method of your application with that command instead of server command. That way your application will be executed without running a server.
I wanted to do sth similar to what you want. (Considering ExampleApp
as main Application
class of my code) I wanted to write a test to make sure that there is no exception parsing the configuration. (Because KotlinModule()
should have beed registered to environment.objectMaooer
in initialize
method of app, otherwise we would have had a runtime error.) I achieved it with sth similar to:
import io.dropwizard.cli.EnvironmentCommand
import io.dropwizard.setup.Bootstrap
import io.dropwizard.setup.Environment
import com.example.config.ExampleConfiguration
import net.sourceforge.argparse4j.inf.Namespace
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class DummyCommand(app: DummyApp) : EnvironmentCommand<ExampleConfiguration>(app, "dummy", "sample test cmd") {
var parsedConfig: ExampleConfiguration? = null
override fun run(environment: Environment, namespace: Namespace, configuration: ExampleConfiguration) {
parsedConfig = configuration
}
}
class DummyApp : ExampleApp() {
val cmd: DummyCommand by lazy { DummyCommand(this) }
override fun initialize(bootstrap: Bootstrap<ExampleConfiguration>) {
super.initialize(bootstrap)
bootstrap.addCommand(cmd)
}
}
class ExampleAppTest {
@Test
fun `Test ExampleConfiguration is parsed successfully`() {
val app = DummyApp()
app.run("dummy", javaClass.getResource("/example-app-test/test-config.yml").file)
val config = app.cmd.parsedConfig
assertNotNull(config)
assertEquals("foo", config.nginxUsername)
}
}
Upvotes: 0