Reputation: 1524
I have this application with a database on its back-end, and I'm having a lot of trouble wrapping my head around how to test this thing. (It's an Android app, but I think that the testing concepts are similar. In my application under test, I have a database adapter:
public class MyDatabaseAdapter() {
Cursor returnCursorFromQuery(SQLQuery query) {
// execute an SQL query and wrap the result in a Cursor object
}
}
I have a method, and I'm trying to test that it gives the right output when my database SELECT query returns no rows:
MyDatabaseAdapter adapter;
public int methodUnderTest() {
this.adapter = new MyDatabaseAdapter();
return populate();
}
private int populate() {
SQLQuery query = new SQLQuery("SELECT * FROM my_table");
Cursor aCursor = this.adapter.returnCursorFromQuery(query);
// populate the UI
return aCursor.getCount();
}
I have a mock cursor object that returns zero rows against all queries in my testing framework, what I don't understand is how I get my private populate()
method to run its query against the mock cursor object rather than the cursor connected to my actual database. Or if I write a mock database adapter object, how to I get the methodUnderTest()
to use the mock adapter instead of the one that it's programmed to use?
Any direction would be really helpful. Thanks.
Upvotes: 1
Views: 802
Reputation: 14640
You can make MyDatabaseAdapter
implement an IDatabaseAdapter
interface, and then create a mock MockDatabaseAdapter
that returns what you want to test. Then instead of setting this.adapter = new MyDatabaseAdapter();
in MethodUnderTest
set this.adapter
in the constructor of the class, from a passed-in parameter of type IDatabaseAdapter:
public MyClass(IDatabaseAdapter adapter)
{
this.adapter = adapter;
}
Then you can pass in new MyDatabaseAdapter()
in the production code and an instance of the mock class in the unit tests.
Upvotes: 1