当前位置: 首页 > 知识库问答 >
问题:

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

茹航
2023-03-14
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:连接尝试失败时,所有这些测试用例都失败了。和NullPointerException异常,因为它没有获取信息。

我对spring boot framework和JUnit几乎是新手,希望帮助我理解这一点以及编写单元测试用例的正确方法

共有1个答案

秦景福
2023-03-14

Spring Boot@controller测试通常使用@webmvctestmockmvc编写。当前的方法不能验证@RequestMapping@ExceptionHandler或其他web注释设置。

看看官方测试Web层教程,一个简单的控制器测试应该是这样的:

@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")));
  }
}

如果您使用例如新SSRIDMAppingController()创建bean,那么使用SpringJunit4ClassRunner是没有意义的。通过使用new,您没有使用任何Spring特性,例如@autowiredbean注入不会发生。

 类似资料:
  • 我一直在学习使用Jest库编写JavaScript/TypeScript代码的单元测试。下面是一个我不知道如何处理的例子。它是用TypeScript输入的——只有两个公共方法和一个构造函数需要service1参数。 我想我需要测试两种情况: > 如果 函数为空。我没有在代码中看到它的任何实现,也不知道它是如何工作的。我应该把它作为参数传递给这个类的实例吗? 我很困惑,在这个特定的例子中,我应该使用

  • 问题内容: 我有一个Java课。如何进行 单元测试? 就我而言,我有课做一个二进制和。它需要两个数组,将它们求和,然后返回一个新的二进制数组。 问题答案: 使用正确的输入定义正常情况下的预期和期望输出。 现在,通过声明一个类来实现测试,将其命名为任何东西(通常是类似TestAddingModule之类的东西),并向其添加testAdd方法(即,类似于下面的方法): 编写一个方法,并在其上方添加@T

  • 我不会告诉你有关后台任务的单元测试的任何内容,因为Hangfire没有添加任何特定方法 (除了 IJobCancellationToken 接口参数)去改变任务。使用您最喜爱的工具,并照常写入单元测试。本节介绍如何测试创建的后台任务。 所有的代码示例都使用静态 BackgroundJob 类来告诉你如何做这个或那些东西,只是出于简单演示的目的。但是当你想测试调用的静态方法时,会变得很痛苦。 不用担

  • 试图弄清楚我是否可以使用spring kafka和spring kafka测试为@KafkaListener编写单元测试。 我的听众课。 我的测试类别: 我的测试配置类: 有什么简单的方法可以做到这一点吗? 或者我应该以其他方式测试@KafkaListener?在单元测试中,如何确保在Kafka中收到新消息时调用@KafkaListener。

  • 我在java中使用mockito编写单元测试。 这就是我要测试的声明。 电影是电影名称的集合,是识别电影的关键。 我嘲笑了守望者班 Mockito.when(watcher.watch(Matchers.any(Set.class))) “thenReturn”中包括什么??