如何编写spring boot controller类单元测试用例

时间:2019-02-22 17:38:35

标签: java unit-testing spring-boot junit4

我正在尝试为Spring Boot控制器类编写JUnit测试用例。控制器代码如下:

package com.test.dashboard.controllers;

import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;
import com.slb.dao.PostGresDAO;

@RequestMapping("/getssrid")
@CrossOrigin(origins = "*")
@RestController
public class SSRIDMAppingController {

    private static final Logger LOGGER = Logger.getLogger(SSRIDMAppingController.class.getName());
    @Autowired
    CounterService counterService;
    @Autowired
    PostGresDAO postGresDAO;

    @CrossOrigin(origins = "*")
    @RequestMapping(method = RequestMethod.GET, value = "/getdbssridlz")
    public @ResponseBody String getSSRIdslz() {
        long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "Request Recieved for getdbssrid at {0}", startTime);
        try {
            counterService.increment("SSRIDMappingCatalog.hitCounter");
            String response = postGresDAO.listMappings("lz");
            counterService.increment("SSRIDMappingCatalog.successfulhitCounter");
            LOGGER.log(Level.INFO, "Request Successfully for getdbssrid  completed in  "
                    + ((System.currentTimeMillis()) - startTime) + " ms");
            Gson gson = new Gson();
            return response;

        } catch (Exception e) {
            counterService.increment("SSRIDMappingCatalog.failurehitCounter");
            LOGGER.log(Level.SEVERE, "Exception occur", e);
            return null;
        }
    }

    @CrossOrigin(origins = "*")
    @RequestMapping(method = RequestMethod.GET, value = "/deldbssridlz")
    public @ResponseBody String delSSRIdslz() {
        return postGresDAO.delSSRIdslz();

    }

    @CrossOrigin(origins = "*")
    @RequestMapping(method = RequestMethod.GET, value = "/deldbssrid")
    public @ResponseBody String delSSRIds() {
        return postGresDAO.delSSRIds();

    }

    @CrossOrigin(origins = "*")
    @RequestMapping(method = RequestMethod.GET, value = "/getdbssrid")
    public @ResponseBody String getSSRIds() {
        long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "Request Recieved for getdbssrid at {0} ", startTime);
        try {
            counterService.increment("SSRIDMappingCatalog.hitCounter");
            String response = postGresDAO.listMappings("dz");
            counterService.increment("SSRIDMappingCatalog.successfulhitCounter");
            LOGGER.log(Level.INFO, "Request Successfully for getdbssrid  completed in  "
                    + ((System.currentTimeMillis()) - startTime) + " ms");
            return response;

        } catch (Exception e) {
            counterService.increment("SSRIDMappingCatalog.failurehitCounter");
            LOGGER.log(Level.SEVERE, "Exception occur", e);
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/alltables/{dbName}")
    @CrossOrigin(origins = "*")
    public @ResponseBody String getTables(@PathVariable("dbName") String dbName) {
        long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "Request Recieved for alltables at {0} ", startTime);
        try {

            counterService.increment("SSRIDMappingCatalog.hitCounter");
            String response = postGresDAO.getTables(dbName);
            counterService.increment("SSRIDMappingCatalog.successfulhitCounter");
            LOGGER.log(Level.INFO, "Request for alltables Successfully completed in  "
                    + ((System.currentTimeMillis()) - startTime) + " ms");
            return response;
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception occur", e);
            counterService.increment("SSRIDMappingCatalog.failurehitCounter");
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/allsources/{appName}")
    @CrossOrigin(origins = "*")
    public @ResponseBody String getSources(@PathVariable("appName") String appName) {
        long startTime = System.currentTimeMillis();
        LOGGER.log(Level.INFO, "Request Recieved for allsources at {0} ", startTime);
        try {
            counterService.increment("SSRIDMappingCatalog.hitCounter");
            String response = postGresDAO.getDbSchema(appName);
            counterService.increment("SSRIDMappingCatalog.successfulhitCounter");
            LOGGER.log(Level.INFO, "Request for allsources Successfully completed in  "
                    + ((System.currentTimeMillis()) - startTime) + " ms");
            return response;
        } catch (Exception e) {
            counterService.increment("SSRIDMappingCatalog.failurehitCounter");
            LOGGER.log(Level.SEVERE, "Exception occur", e);
            return null;
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = "/delsources/{appName}")
    @CrossOrigin(origins = "*")
    public @ResponseBody String getSourcesDel(@PathVariable("appName") String appName) {

        return postGresDAO.delDbSchema(appName);

    }

    @RequestMapping(method = RequestMethod.GET, value = "/deltables/{dbName}")
    @CrossOrigin(origins = "*")
    public @ResponseBody String getTablesDel(@PathVariable("dbName") String dbName) {

        return postGresDAO.delTables(dbName);

    }

}

我正在尝试编写简单的测试用例,如下所示:

package com.test.dashboard.controllers;

import org.junit.*;
import org.junit.runner.RunWith;

import static org.junit.Assert.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.metrics.CounterService;
import org.springframework.boot.actuate.metrics.buffer.BufferCounterService;
import org.springframework.boot.actuate.metrics.buffer.CounterBuffers;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;

import com.slb.dao.PostGresDAO;

@RunWith(SpringJUnit4ClassRunner.class)
public class SSRIDMAppingControllerTest {
    @Test
    public void testSSRIDMAppingController() throws Exception {
        SSRIDMAppingController result = new SSRIDMAppingController();
        assertNotNull(result);
    }

    @Test
    public void testDelSSRIds() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String result = fixture.delSSRIds();
        assertNotNull(result);
    }

    @Test
    public void testDelSSRIdslz() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String result = fixture.delSSRIdslz();
        assertNotNull(result);
        assertEquals("Fail", result);
    }

    @Test
    public void testGetSSRIds() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String result = fixture.getSSRIds();
        assertEquals("Fail", result);
    }

    @Test
    public void testGetSSRIdslz() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String result = fixture.getSSRIdslz();
        assertNotNull(result);
    }

    @Test
    public void testGetSources() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String appName = "test";
        String result = fixture.getSources(appName);
        assertEquals("test", result);
    }

    @Test
    public void testGetSourcesDel() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String appName = "test";
        String result = fixture.getSourcesDel(appName);
        assertEquals("test", result);
    }

    @Test
    public void testGetTables() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String dbName = "test";
        String result = fixture.getTables(dbName);
        assertNotNull(result);
        assertEquals("test", result);
    }

    @Test
    public void testGetTablesDel() throws Exception {
        SSRIDMAppingController fixture = new SSRIDMAppingController();
        fixture.counterService = new BufferCounterService(new CounterBuffers());
        fixture.postGresDAO = new PostGresDAO();
        String dbName = "lz_test_db";
        String result = fixture.getTablesDel(dbName);
        assertNotNull(result);
        assertEquals("lz_test_db", result);
    }
    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {
    }

    public static void main(String[] args) {
        new org.junit.runner.JUnitCore().run(SSRIDMAppingControllerTest.class);
    }
}

所有这些测试用例都以某种方式失败,因为它试图连接数据库并获得org.postgresql.util.PSQLException: The connection attempt failed。和NullPointerException异常,因为它没有获取信息。

对于Spring Boot框架和JUnit来说,我是一个新手,正在寻求帮助以了解这一点以及编写单元测试用例的正确方法。

1 个答案:

答案 0 :(得分:1)

通常使用@WebMvcTestMockMvc编写Spring Boot @Controller测试。您当前的方法无法验证@RequestMapping@ExceptionHandler或其他Web注释设置。

看看官方的Testing the Web Layer教程,简单的控制器测试应如下所示:

@RunWith(SpringRunner.class)
@WebMvcTest
public class WebLayerTest {

  @Autowired
  private MockMvc mockMvc;

  @Test
  public void shouldReturnDefaultMessage() throws Exception {
    this.mockMvc.perform(get("/"))
        .andExpect(status().isOk())
        .andExpect(content().string(containsString("Hello World")));
  }
}

如果使用SpringJUnit4ClassRunner创建bean,例如,使用new是没有意义的。 new SSRIDMAppingController()。通过使用new,您没有使用任何Spring功能,例如@Autowired不会进行bean注入。