Dropwizard: How to stop service programmatically

前端 未结 5 747
花落未央
花落未央 2021-01-04 06:13

To start the service, I know one uses new MyService().run(args). How to stop it?

I need to start and stop programmatically for setUp() and

5条回答
  •  -上瘾入骨i
    2021-01-04 07:03

    Thanks @LiorH for this great suggestion.

    Here is a complete test class using the DropwizardServiceRule in dropwizard-0.6.2.

    First create a service configuration for testing: testing-server.yml and place it in the test's class path (ex. src\test\resources). This way you can set different ports for the test service to use:

    http:
      port: 7000
      adminPort: 7001
    

    A simple test class that checks if there is a resource at the location "/request" looks like this:

    class TheServiceTest {
    
        @ClassRule
        public static DropwizardServiceRule RULE = new DropwizardServiceRule(TheService.class,
                Resources.getResource("testing-server.yml").getPath());
    
        @Test
        public void
        dropwizard_gets_configured_correctly() throws Exception {
            Client client = new Client();
    
            ClientResponse response = client.resource(
                    String.format("http://localhost:%d/request", RULE.getLocalPort()))
                            .get(ClientResponse.class);
    
            assertThat(response.getStatus(), is(200));
        }
    }
    

    I have also added the import in case you do not know what implementation to choose.

    import com.google.common.io.Resources;
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.yammer.dropwizard.testing.junit.DropwizardServiceRule;
    import org.junit.ClassRule;
    import org.junit.Test;
    import org.junit.rules.TestRule;
    
    import static org.hamcrest.core.Is.is;
    import static org.junit.Assert.assertThat;
    

    At the end of the tests, the server will shutdown gracefully, so you do not need to worry about it.

提交回复
热议问题