How to use JUnit4 for unit testing in SpringBoot

From DevelopWiki
Jump to: navigation, search

Overview[edit]

This article describes how to use Junit4 for unit testing under the SpringBoot framework.

There are total four cases.

Simple Tests[edit]

This is the simplest unit test, which is suitable for unit testing of code such as the Utils Class, Service code and DAO code. The method to be tested will be called directly.

package com.developwiki;

import static org.junit.Assert.*;

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;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
	
	@Autowired
	private yourService service;

	/**
	 * test service method directly
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Test
	public void testYourMethod() {
		service.yourMethod();
	}
	
	/**
	 * Test utils method directly
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Test
	public void testYourUtil(){
		UtilsName.utilsMethod();
	}
}

Simulate the HTTP request test[edit]

The following is a good way to test the Controller method by simulating HTTP requests

package com.developwiki;

import org.junit.Assert;
import org.junit.Before;
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 org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
	
	private MockMvc mockMvc;
	
	@Autowired
    private WebApplicationContext webApplicationContext;

	/**
	 * pretreatment
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Before
    public void before() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }
	
	/**
	 * test controller method by http
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Test
    public void testYourMethod() throws Exception {
        MvcResult mvcResult = mockMvc
            .perform(MockMvcRequestBuilders.get("/developwiki/findById")
                .param("id", "1234"))
            .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String responseString = mvcResult.getResponse().getContentAsString();
        //test status
        Assert.assertEquals("request error", 200, status);
        //print output
        System.out.println("return result:"+responseString);
    }
}

Simulate the HTTP request test with session[edit]

When testing a method in a system, it is often blocked by the interceptor of the system and jump to the login page.

In this case, you need to log in and get the session before the test, and then carry the session to unit testing.

package com.developwiki;

import org.junit.Assert;
import org.junit.Before;
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.mock.web.MockHttpSession;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SimpleTest {
	
	private MockMvc mockMvc;
	private MockHttpSession session;
	
	@Autowired
    private WebApplicationContext webApplicationContext;

	/**
	 * pretreatment
     * simulate login and get session
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Before
    public void before() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        //simulate login and get session
        session = new MockHttpSession();
        MvcResult mvcResult = mockMvc
              .perform(MockMvcRequestBuilders.get("/login")
              		.param("username", "developwiki.com")
              		.param("password", "developwiki.com")
              		.session(session))
              .andReturn();
      int status = mvcResult.getResponse().getStatus();
      Assert.assertEquals("login error", 200, status);
    }
	
	/**
	 * simulate http request
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Test
    public void testYourMethod() throws Exception {
        MvcResult mvcResult = mockMvc
                .perform(MockMvcRequestBuilders.get("/developwiki/findById")
                		.param("id", "1234")
                		.session(session))
                .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String responseString = mvcResult.getResponse().getContentAsString();
        //test status
        Assert.assertEquals("test status", 200, status);
        //print response
        System.out.println("test response:"+responseString);
    }
}

Transaction automatic rollback test[edit]

When testing a method in a system, we often need save or delete data of database. If we don't want the data to be really added or removed, we need to do unit testing in this way.

This way will automatically roll back the transaction to avoid generating useless data or deleting important data.

package com.developwiki;

import org.junit.Assert;
import org.junit.Before;
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.mock.web.MockHttpSession;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.context.WebApplicationContext;

@RunWith(SpringRunner.class)
@SpringBootTest
@Rollback(value=true)
@Transactional
public class SimpleTest {
	
	private MockMvc mockMvc;
	private MockHttpSession session;
	
	@Autowired
    private WebApplicationContext webApplicationContext;

	/**
	 * pretreatment
	 * simulate login and get session
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Before
    public void before() throws Exception {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        //simulate login and get session
        session = new MockHttpSession();
        MvcResult mvcResult = mockMvc
              .perform(MockMvcRequestBuilders.get("/login")
              		.param("username", "developwiki.com")
              		.param("password", "developwiki.com")
              		.session(session))
              .andReturn();
      int status = mvcResult.getResponse().getStatus();
      Assert.assertEquals("login error", 200, status);
    }
	
	/**
	 * test method
	 * this method will rollback
	 * @author developwiki
	 * @author zh.developwiki.com
	 * @author www.developwiki.com
	 */
	@Test
    public void testYourMethod() throws Exception {
        MvcResult mvcResult = mockMvc
                .perform(MockMvcRequestBuilders.get("/developwiki/findById")
                		.param("id", "1234")
                		.session(session))
                .andReturn();
        int status = mvcResult.getResponse().getStatus();
        String responseString = mvcResult.getResponse().getContentAsString();
        //test status
        Assert.assertEquals("status error", 200, status);
        //test response
        System.out.println("print response:"+responseString);
    }
}