born to fly
born to fly

Reputation: 21

Creating a ResultSet Object by myself

I want to create a Testclass for a class, which reads data from a database and convert them. The testclass should test this convert function. But that I can test this function I need a ResultSet object.

How can I fill some data in the ResultSet Object without a connection to a Database?

Upvotes: 2

Views: 4967

Answers (2)

AlexWien
AlexWien

Reputation: 28727

Something similar to the code below: You need an Interface for your Db access. This interface you use in code and test code: myDbConnectionMock is a Mock object which has the same interface like the Db connection, but it is an object that you create and where you cann fill in what you want:

i would not use Mockito or worse EasyMock.

code i have typed in the texteditor (hopefully compileable, maybe not):

public void testDBConnection() {

  IDataBaseConnection conn = new MyDbConnectionMock();

  conn.connect();
  Set<Result> result = conn.readData();

  assertTrue(result.size > 0);
}

where

 // Interface for DB connection, adapt to real DB connection
    public interface IDataBaseConnection {
       boolean connect();
       Set<Result> readData();
    }

and

// DB connection Mock
class MyDbConnectionMock implements IDbConnection {
  public void connect() {
     return true;
  }

  public Set<ResultSet> readData() {
     Set<Result> resultSet = new HashSet<Result>();
     Result res1 = new Result(20);
     resultSet.add(res1);

     Result res1 = new Result(30);
     resultSet.add(res2);
     return resultSet;
   }
}

Upvotes: 1

Mik378
Mik378

Reputation: 22171

Reading from databases concerns integration testing, not unit testing. So, you can and should use the original ResultSet since an integration test takes real backends (like your database) in account.

If you attempt to unit test your logic, stub or mock your specific DAO called part in order to return sample data to be tested. But don't invoke database (don't deal with ResultSet) at all in this case.

Upvotes: 1

Related Questions