如何通过使用Mockito模拟数据库连接来测试Servlet类

时间:2019-10-21 01:32:20

标签: java unit-testing servlets junit mockito

我正在尝试在一个旧项目上进行一些单元测试(我正在学习该主题),但是我不知道如何模拟数据库(我正在使用Mockito)并测试{{1 }} 方法。 (现在,我几乎可以在没有数据库连接的情况下测试方法和类)

我已经尝试过许多在互联网上找到的方法,例如this

doGet

但是我不确定如何修改它以满足我的需求。 我的代码如下:

JavaConnectDB.java

package com.javacodegeeks;

import java.sql.Connection;
import java.sql.Statement;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

public class DBConnectionTest {

  @InjectMocks private DBConnection dbConnection;
  @Mock private Connection mockConnection;
  @Mock private Statement mockStatement;

  @Before
  public void setUp() {
    MockitoAnnotations.initMocks(this);
  }

  @Test
  public void testMockDBConnection() throws Exception {
    Mockito.when(mockConnection.createStatement()).thenReturn(mockStatement);
    Mockito.when(mockConnection.createStatement().executeUpdate(Mockito.any())).thenReturn(1);
    int value = dbConnection.executeQuery("");
    Assert.assertEquals(value, 1);
    Mockito.verify(mockConnection.createStatement(), Mockito.times(1));
  }
}

GetUsuario.java


import java.sql.Connection;
import java.sql.DriverManager;

public class JavaConnectDb {

public static Connection connectDbH() {
   try {
       Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.4:1521:ORCL18", "c##foo", "foo");

        } catch (Exception e) {
            System.err.println(e);
        }
        return conn;

    }

我想在/** * Servlet implementation class GetUsuario */ @WebServlet("/GetUsuario") public class GetUsuario extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public GetUsuario() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub getInfoCookies(request,response); Connection conn = g.co.hosp.JavaConnectDb.connectDbH(); response.setContentType("text/html"); PrintWriter out = response.getWriter(); try{ String sql = "select * from usuario"; OraclePreparedStatement pst = (OraclePreparedStatement) conn.prepareStatement(sql); OracleResultSet rs = (OracleResultSet) pst.executeQuery(); String outPutTable = "<table><thead><tr><th>ID</th><th>USUARIO_ID</th><th>NOMBRE</th><th>APELLIDO</th><th>USUARIO</th><th>ESPECIALIDAD_ID</th></tr></thead>"; while(rs.next()){ outPutTable += "<tr><td>"+rs.getString(1)+"</td>"+"<td>"+rs.getString(3)+"</td>"+"<td>"+rs.getString(4)+"</td>"+"<td>"+rs.getString(5)+"</td>"+"<td>"+rs.getString(6)+"</td>"+"<td>"+rs.getString(7)+"</td></tr>"; } outPutTable+="</table>"; out.println(outPutTable); conn.close(); }catch(Exception e){ System.err.println(e); }finally{ out.close(); } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } protected void getInfoCookies(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ Cookie[] cookiesInf = request.getCookies(); if(cookiesInf !=null){ for(Cookie cookie : cookiesInf){ if(cookie.getName().equals("hosp")){ hosp = Integer.parseInt(cookie.getValue()); } } } } } 上运行单元测试,但是我不确定该怎么做...

0 个答案:

没有答案