Reputation: 6578
I want to test the next function in java using EasyMock, Mock or Mockito. I want to test that when I call to leerCantPueblos() function, the query("SELECT conarpueblos()") is executed.
private void leerCantPueblos(){
cantPueblosBD = leerBD.cantidadPueblos();
try {
while(cantPueblosBD.next()){
CANTIDADPUEBLOS = cantPueblosBD.getInt("contarpueblos");
}
} catch (SQLException e) {e.printStackTrace();}
}
this function call to cantidadPueblos(), that is the next function.
public ResultSet cantidadPueblos() {
try {
sentencia = conexion.createStatement();
ResultSet cantidadPueblos = sentencia.executeQuery("SELECT contarpueblos()");
return cantidadPueblos;
} catch (SQLException e) {}
return null;
}
I try with the next JUnit test but throws nullpointerexception
package tests;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import org.easymock.Mock;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import server.ConexionBD;
public class TestBD {
@InjectMocks
ConexionBD conexionDB;
@Mock
Connection conexion;
@Mock
Statement sentencia;
@Before
public void setup() throws SQLException {
MockitoAnnotations.initMocks(this);
//Mockito.initMocks(this);
Mockito.when(conexion.createStatement()).thenReturn(sentencia);
}
@Test
public void cantidadPueblos_shouldExecuteQuery() throws SQLException {
conexionDB.cantidadPueblos();
Mockito.verify(sentencia).executeQuery("SELECT contarpueblos()");
}
}
The next row fail:
Mockito.when(conexion.createStatement()).thenReturn(sentencia);
Upvotes: 1
Views: 5605
Reputation: 2568
The test looks good except of the first line of setup
method.
public void setup() throws SQLException {
sentencia = conexion.createStatement();
MockitoAnnotations.initMocks(this);
//Mockito.initMocks(this);
Mockito.when(conexion.createStatement()).thenReturn(sentencia);
}
It throws NPE as conexion.createStatement()
is invoked before mocks are initialized. Just remove sentencia = conexion.createStatement();
line, it is redundant here.
import org.easymock.Mock
should be replaced by import org.mockito.Mock;
Upvotes: 1