开发者

Mechanics of testing with a mock database connection

开发者 https://www.devze.com 2023-01-23 15:35 出处:网络
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 a

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 resul开发者_Go百科t 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号