Micronaut unit testing : need clarification on @MicronautTest

Viewed 2399

I am trying my hands on micronaut, I am facing some difficulty in understanding how to do unit tests.

I have a simple application with only one controller(which returns hello).
Now I want to test this endpoint. Coming from springboot I was expecting that micronaut has some runner class like SpringRunner, I could not find any. Is there a runner class in micronaut for running tests?

From the documentation here I see that I can test my rest endpoints using HTTPClient. I tried both the

  1. Low level HttpClient
  2. CompileTime HttpClient

Here is a snippet of the test classes I have

@MicronautTest
class HelloControllerSpec {
    @Inject
    EmbeddedServer server; 

    @Inject
    @Client("/")
    HttpClient client; 

    @Test
    void testHelloWorldResponse() {
          //client and server are null
           .........
    }
}  

And

@MicronautTest 
public class HelloClientSpec  {

    @Inject
    HelloClient client; 

    @Test
    public void testHelloWorldResponse(){
        //client is null
   }
}

From what I observed, the annotation @MicronautTest doesn't seem to do anything. Its the same case with @Inject and @Client, all the fields are null when I run the test. So I am wondering what exactly does @MicronautTest do?

The only way I could get it work is to start the server explicitly(@Inject on EmbeddedServer doesn't do anything) like this

server = ApplicationContext.run(EmbeddedServer.class);
helloClient = server.getApplicationContext().getBean(HelloClient.class);

Even with this, it starts a server instance. Which in not what I wanted. Because I do not want to start server for unit tests. Also I do not want to get the beans this way from application Contexts. Whay doesn't @Inject, @Client, @EmbeddedServer work in my case, am I missing something here?

In case of springboot, I could test only the weblayer separately(using mockmvc and springboottest), not starting the whole application context. is there an equivalent in micronaut?

I am using micronaut 1.0.2

1 Answers

For anyone who encounters this issue. Here are a few hints. This is what solved the issue in my case. Humble mention to Jeff Scott Brown, whose suggestions pushed me in the right direction.

  1. Please check the micronaut version,
    I had micronaut 1.0.2 version installed through which I generated the app. But the documentation I was following was of latest version which is 1.2.3

  2. Please check which junit version you have in your pom or build file. If you generate the app with latest(1.2.3) you will have Junit-5 and Jupiter dependencies, If you are using older(1.0.2) versions, you will have Junit4.
    For the annotation @MicronautTest to work you need Junit5

Related