问题描述
我正在尝试为 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楼
Spring Boot @Controller
测试通常使用和 。
您当前的方法不会验证@RequestMapping
、 @ExceptionHandler
或其他 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")));
}
}
如果您使用new
例如new SSRIDMAppingController()
创建 bean,则使用SpringJUnit4ClassRunner
毫无意义。
通过使用new
您不会使用任何 Spring 功能,例如@Autowired
bean 注入不会发生。