0

I'm trying to do some unit tests (I'm learning the topic) on an old project, however I have no idea whatsoever on how to mock a DB (I'm using mockito) and test the doGet method. (right now I'm pretty much just able to test methods and classes without a db connection)

I have already tried many methods I found on the internet like this

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

But I'm just not sure how to modify it to fit my needs. my code looks like this:

JavaConnectDB.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;

    }

GetUsuario.java

/**
 * 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());
                    }
                }
            }
        }
}

I want to run a Unit Test on the doGet but I'm simply not sure what to do...

Sabir Khan
  • 9,826
  • 7
  • 45
  • 98
Matt
  • 25
  • 4
  • so you are not sure how to ignore / mock `Class.forName`? – Sabir Khan Oct 22 '19 at 05:30
  • @SabirKhan I'm trying to make a unit test of the doGet method. the thing is as it is the first time I'm doing a unit test for a servlet like this, i have no idea on how to proceed and can't find anything (or at least anything that i can understand) on the internet. I didn't add my test class because it's pretty much filled with nonsense at this point. Thank you for your time. – Matt Oct 22 '19 at 06:15
  • It would be easy to help if you tell what you tried & where you struggling. If you wish to mock your DB connection call, its better to mock `Connection connectDbH()` method itself i.e. there is no point in letting the control go inside that method. I am not sure about current status but mocking static & final classes was not supported in mockito but was supported in powermock & easymock. – Sabir Khan Oct 22 '19 at 06:22
  • See [answer](https://stackoverflow.com/a/19466349/3850730) – Sabir Khan Oct 22 '19 at 06:24
  • @SabirKhan Ok, i will try mocking `Connection connectDbH()` and see how it goes. I will also try powermock and easymock. Thank you very much for your answer. ps: I will comment again to keep you posted on if I manage to do it (Not a big fan of letting people with curiosity of how it ended...) – Matt Oct 23 '19 at 16:08
  • 1
    @SabirKhan Hello, just letting you know that mocking `Connection connectDbH()` did the trick. I also tried using powermock and once I understood how it worked i managed to do the unit testing i wanted. Thank you for your time. – Matt Oct 27 '19 at 18:47

0 Answers0