Hello WebEngine! Hello WebEngine!

I've already written about WebEngine, and I've written about unit testing, but I haven't written about WebEngine AND unit testing. Let's fix this with a little example. If you don't already know our testing framework I suggest that you read a previous post on how to test operations or our test framework documentation.

Hello WebEngine


So this is a very simple WebEngine module that returns a String "Hello WebEngine." And we want to make sure that when we hit the /hello/ url, we get that hello.

[java]
@Path("/hello")
@Produces("text/html;charset=UTF-8")
@WebObject(type = "MyRoot")
public class MyRoot extends ModuleRoot {

@GET
public Object doGet() {
    return "Hello WebEngine";
}

[/java]

To make sure this happens, we can set up a unit test that deploys our WebEngine module in a Jetty test server. It's really easy to do thanks to JUnit4 runners. We've written our own that starts Jetty and deploys the necessary Nuxeo bundles for your tests. As you can see in the code below all you need to do is select the right feature. In our case I've chosen the RestFeature. What does it get us? I won't list all the bundles deployed but you'll have Nuxeo's runtime to handle the bundles and services, the core layer configured by default with an embedded H2 database and access to many services like directories, login, security, document types, WebEngine, automation etc...

The next step is to deploy our own code that we want to test. This is the Deploy annotation. I've also changed Jetty's port to 18080 since my 8080 is usually taken by a local server. Now we have everything we need to test our WebEngine module. Let's write the actual test:

[java]
@RunWith(FeaturesRunner.class)
@Features(RestFeature.class)
@Jetty(port = 18080)
@Deploy("WebEngineHelloTest")
public class HelloWorldTest {

@Test
public void testHello() throws HttpException, IOException {
    HttpClient httpClient = new HttpClient();
    GetMethod get = new GetMethod("http://localhost:18080/hello/");
    int statusCode = httpClient.executeMethod(get);
    assertEquals(200, statusCode);
    String response = get.getResponseBodyAsString();
    assertEquals(response, "Hello WebEngine");
}

}
[/java]

It is pretty easy. I take HttpClient and simply execute a Get method on my module URL. I then verify that the return code is 200 and that the content of the response is "Hello WebEngine".

That's it, we've been through a basic WebEngine test setup. I'll try to add this in an IDE wizard before the next release, as well as other cool stuff. Let me know if there is something particular you would like to see in the IDE or in an upcoming blog post. See ya next Friday!