Search code examples
testingcodenameonefunctional-testing

How to mock server / http requests in Codename One for testing?


I want to write functional tests for my Codename One app.

To do this, I need to be able to mock some server responses, so that they return exactly what I need for the specific test.

One thing that I tried to make the functions that send the HTTP requests take ConnectionRequest as a parameter, this way I can inject something to simulate network latency and then call the callback with the mocked response.

However, when I try to inject the mocks of ConnectionRequest in the prepare method of a unit test, they are still injected after the app is started, which does not work for my case, since I sent HTTP request on the start of the app.

Is it possible to mock ConnectionRequest or do something equivalent before starting the app?


Solution

  • Here is what I ended up doing. I am posting this if someone needs a workaround for the automated tests.

    1. Write an interface called HTTPRequestInterface, which exposes the neccessary methods to construct an HTTP query
    2. Create an implementation of HTTPRequestInterface called say HTTPRequest, which is just a wrapper around ConnectionRequest
    3. Create a class for creating HTTPRequests, say HTTPRequestFactory, which has a static method called create and a method called setMock. This class creates a normal HTTPRequest in case no mock was set and the specified mock in case a mock was set.
    4. Replace all ConnectionRequest with HTTPRequestFactory.create()
    5. Create a class InitialSetup, which has two methods: setInitialization, which accepts a Runnable to be executed, and init method, which just runs the Runnable.
    6. In the start method, call InitialSetup.init
    7. Now in the tests, in the prepare method, I can set the desired mock, and the app when not running automated tests will send queries to the actual server.

    Requires some effort, but the automated tests with mocked backend bring confidence that I think is definitely worth it!