1

I wrote DAO class

public List<ClassRoom> getAllClassRooms() {
    List<ClassRoom> classRoomsList = new ArrayList<>();
    String sqlStatement = "SELECT * FROM university.classrooms;";
    try {
        Class.forName("org.postgresql.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    Connection connection = null;
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    try {
        connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/Exam6", "postgres", "Navlanart1");
        try {
            statement = connection.prepareStatement(sqlStatement);
            try {
                resultSet = statement.executeQuery();
                while (resultSet.next()) {
                    ClassRoom classRoom = new ClassRoom(resultSet.getString("name"));
                    classRoomsList.add(classRoom);
                }
            } catch (SQLException e) {
            } finally {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return classRoomsList;
}

Now i want to test it by class like that

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.powermock.api.easymock.PowerMock.mockStatic;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PrepareForTest;

import com.kolosok.university.dao.ClassRoomDao;

@RunWith(MockitoJUnitRunner.class)
@PrepareForTest(DriverManager.class)
public class TestClassRoomDao {

@Mock
Connection mockConnection;

@Mock
PreparedStatement mockPreparedStatement;

@Mock
ResultSet mockResultSet;

@Test
public void testGetAllClassRooms() throws SQLException {

    mockStatic(DriverManager.class);

    when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(mockConnection);
    when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement);
    when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
    when(mockResultSet.next()).thenReturn(Boolean.FALSE);

    ClassRoomDao classRoomDao = new ClassRoomDao();
    classRoomDao.getAllClassRooms();

    verify(mockConnection, times(1)).prepareStatement(anyString());
    verify(mockPreparedStatement, times(1)).executeQuery();
    verify(mockResultSet, times(1)).next();
}

}

But it doesnt work.

java.sql.SQLException: No suitable driver found for 
    at java.sql.DriverManager.getConnection(Unknown Source)
    at java.sql.DriverManager.getConnection(Unknown Source)
    at     com.kolosok.university.TestClassRoomDao.testGetAllClassRooms(TestClassRoomDao.java:58)

I read alot of stackOverFlow answers on similar quastions. But still cant solve my issue

I'm using

postgresql-42.0.0.jre7.jar

mockito-all-1.10.19.jar

powermock-api-easymock-1.6.6.jar

powermock-core-1.6.6.jar

cglib-nodep-3.1.jar

javassist-3.12.1.GA.jar

objenesis-2.5.jar

powermock-api-mockito-1.6.6.jar

powermock-api-support-1.6.6.jar

easymock-3.4.jar

Anton Kolosok
  • 482
  • 9
  • 24
  • Possible duplicate of [Mocking static methods with Mockito](http://stackoverflow.com/questions/21105403/mocking-static-methods-with-mockito) – M. Prokhorov Mar 29 '17 at 14:17

2 Answers2

0

I think the problem may be that you are not running this with the PowerMockRunner, so the PowerMock extensions to are using ( like mockStatic ) aren't obeyed

Try changing @RunWith(MockitoJUnitRunner.class) to @RunWith(PowerMockRunner.class)

EDIT

You may also need to initialize the mocks. Easiest way is to use an @Before method, something like

@Before public void setup(){ initMocks(this); }

DaveH
  • 7,187
  • 5
  • 32
  • 53
  • Have been trying it early, always got this - PowerMockRunner Cannot be resilved to the type – Anton Kolosok Mar 29 '17 at 16:02
  • Ok. I have changed @RunWith(MockitoJUnitRunner.class) to @RunWith(PowerMockRunner.class). Still have same problem. Dont know what im doing wrong. – Anton Kolosok Mar 30 '17 at 07:44
  • Next step is to alter the PrepareForTest annotation. You need to prepare the class that calls the object you're wanting to mock, not the mocked object itself. So, in this case you should @PrepareForTest(nameOfDaoClass) – DaveH Mar 30 '17 at 08:10
  • Thnx a lot. When i make `@RunWith(PowerMockRunner.class) @PrepareForTest(ClassRoomDao.class)` - I"ve got Misplaced argument matcher in line `when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(mockConnection);`. I read some and then `change mockStatic(DriverManager.class);` to `PowerMockito.mockStatic(DriverManager.class);`. Now ive got NullPointerExeption in line `when(mockConnection.prepareStatement(anyString())).thenReturn(mockPreparedStatement);` – Anton Kolosok Mar 30 '17 at 10:10
  • What i have now: 1) I downgrade all jar from 1.6.6 to 1.6.5 (its little bugy according to mockito FAQ) 2) I have `@RunWith(PowerMockRunner.class) @PrepareForTest(ClassRoomDao.class)` then `@Before public void initMocks1() { MockitoAnnotations.initMocks(this); }` and `mockStatic(DriverManager.class);` in this combination Iv got error `org.mockito.exceptions.misusing.invaliduseofmatchersexception` in line `when(DriverManager.getConnection(anyString(), anyString(), anyString())).thenReturn(mockConnection);` – Anton Kolosok Mar 31 '17 at 08:04
  • if I change `mockStatic(DriverManager.class);` to `PowerMockito.mockStatic(DriverManager.class);` I have `java.lang.verifyerror inconsistent stackmap frames at branch target 1069` – Anton Kolosok Mar 31 '17 at 08:04
0
Class Cut{
    public void abc(){
        Connection conn = DriverManager.getConnection("url","username","password");
    }
}


@PrepareForTest({Cut.class})
Class Cut_test{

    cut classUnderTest;

    public void abc_test(){

    PowerMockito.mockStatic(DriverManager.class);
    when(DriverManager.getConnection(anyString(),anyString(),anyString())).thenReturn(mockConnection);

    //test the stub
    Connection conn = DriverManager.getConnection("abc","abc","pass");

    //call actual method 
    classunderTest.abc();

    //Assert
    assertTrue("passed",true);
}

for those getting nullpointerException,

  1. check if the stub is working by adding the lines under //test the stub.
  2. comment out your DriverManager.getConnection in actual code .
  3. replace with //test the stub i posted above .
  4. then run the test method in debug mode and see if it reaches the actual method.
  5. if it didn't reach then add the actual method's class in @PrepareForTest({KafkaRecordHandler.class})
Andronicus
  • 25,419
  • 17
  • 47
  • 88
bohoart
  • 1
  • 2