Как написать весенний загрузчик контроллера класса Unit test case - PullRequest
0 голосов
/ 22 февраля 2019

Я пытаюсь написать тестовый пример JUnit для класса контроллера Spring Boot.код контроллера выглядит следующим образом:

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 failedNullPointerException исключение, так как он не получает информацию.

Я в значительной степени новичок в рамках среды весенней загрузки и JUnit и ищу помощь в понимании этого и правильного способа написания примера модульного теста.

1 Ответ

0 голосов
/ 22 февраля 2019

Тест Spring Boot @Controller обычно пишется с использованием @WebMvcTest и MockMvc.Ваш текущий подход не проверяет @RequestMapping, @ExceptionHandler или другие настройки веб-аннотаций.

Посмотрите официальное руководство Тестирование веб-слоя , простой тест контроллера долженвыглядит так:

@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 внедрение боба не произойдет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...