1

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.

0

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.