Search code examples
spring-bootjunit

How do I annotate my JUnit test so it will run the way my Spring Boot app runs?


I have a Spring Boot web application that I launch by running this class ...

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

The web app has a JSP/HTML front end served up by Spring MVC Controllers which talk to Services which talk to DAOs which uses Hibernate to read/write Entities to a MySQL database.

All the components and services get instantiated and @Autowired and the web app runs fine.

Now, I want to build JUnit tests and test some of the functionality in the Services or the DAOs.

I started writing a JUnit test like below, but I quickly got stuck on not knowing how to instantiate all the @Autowired components and classes.

public class MySQLTests {

    @Test
    public void test000() {
        assertEquals("Here is a test for addition", 10, (7+3));
    }

    @Autowired
    UserService userService = null;
            
    @Test
    public void test001() {
        userService.doSomething("abc123");

        // ...
    }
    
}

I basically want the web application to start up and run, and then have the JUnit tests run the methods in those Services.

I need some help getting started ... is there some kind of JUnit equivalent of the @SpringBootApplication annotation that I can use in my JUnit class?


Solution

  • Answering my own question ... I got it working like this ...

    1. Annotated the test class with:

      @RunWith(SpringRunner.class)

      @SpringBootTest

    2. The test class had to be in a package above the @Controller class ... so my test class is in com.projectname.* and the controller is is com.projectname.controller.*

    The working code looks like this ...

    package com.projectname;
    
    import static org.junit.Assert.assertNotNull;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    import com.projectname.controller.WebController;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest
    public class Test1 {
    
        @Autowired
        private WebController controller;
    
        @Test
        public void contextLoads() throws Exception {
            assertNotNull("WebController should not be null", controller);
        }
        
    }