Skip to content

Embedded test server

Hebert Coelho edited this page Nov 15, 2018 · 1 revision

How to run as Embedded Server on Tests

Maybe you are asking? Why should add this in my tests instead of just add a Mock?

Some reasons are:

  • When you mock your rest calls you do not test your real code. Usually, the code that calls another service is mocked. This part is usually not tested. So maybe on your mocking, you could pass some wrong data and since it is a mock, it would not detect anything wrong
  • This server is really fast and it will not slow down your project like integrated tests
  • With the configuration file you can add this file into your git and share with everybody else.

You can add this to your java tests in two ways:

Pro Tip:

uaiMockServer needs a configuration file to run. You can have one huge file or you can have several files OR You could create one file per request type, this will make the file smaller.

I do believe that if you create one small file per test/class will be better to maintain and to avoid merge conflicts

All you files could be edited using the uaiMockServer GUI. Just run like java -jar uaiMockServer.X.X.X.jar FILE_PATH. It will make easier for you to edit the routes.

Running the code manually

You can add the code below that it will start the server:

@BeforeClass
public static void beforeClass() {
    uaiMockServer = UaiMockServer.start();
}

@AfterClass
public static void afterClass() {
    uaiMockServer.shutdown();
}

This will start the server for you. By default the configuration file name should be: uaiMockServer.json. In case you want a different file name you can pass it as argument like UaiMockServer.start("YOUR_FILE.json").

Using a JUnit Runner

If you want, you can even run this project with annotations!

Without Spring

If you are not a Spring user, run like this:

@RunWith(UaiMockServerRunner.class)
@UaiRunnerMockServerConfiguration(configurationFile = "runnerWithConfigTest01.json")
public class RunningWithAnnotation { }

The annotation @UaiRunnerMockServerConfiguration is optional. You should use only if you need to pass a different configuration file.

With Spring

But if you are a Spring User, than this could be a problem because you need to put the Spring annotation. Fear not my friend, we have a solution for you:

@RunWith(UaiMockServerSpringRunner.class)
@ContextConfiguration(locations = "classpath:spring-context-test.xml")
@UaiRunnerMockServerConfiguration(configurationFile = "uaiMockServer.json")
public class MySpringTestClass {}

Notice that there is a Spring Runner that should be used in case of annotation approach. Also, we could - or not - point the configuration file.