开发者

Android unit testing & using a different database file

开发者 https://www.devze.com 2022-12-25 17:22 出处:网络
I\'m trying to start unit testing on my application (should have done so from the beginning). I\'ve got an Eclipse project structure set up and everything seems to work well, but...

I'm trying to start unit testing on my application (should have done so from the beginning). I've got an Eclipse project structure set up and everything seems to work well, but...

I'm subclassing SQLiteOpenHelper to access the application database. This works well for the application, but when using the same class in the unit tests, it writes to the same database as the actual application. This is obviously rathe开发者_如何学Cr irritating, since unit test data shows up when developing and testing the actual application.

What's the best way to make the SQLiteOpenHelper class write to a different database file when being called from the unit tests?


If you don't have problems with adding some lines of code to your original program, you could also add a class variable and appropriate getter and setter methods to your Application subclass defining if you are in testing mode or not. Your unit test class could then access the setter method and set testing on "true". At the place in your code, where your database is defined, you would then access the getter method to decide which database to take.


You could consider to use the EasyMock library over at easymock.org to mock the SQLiteOpenHelpers subclass and its methods.


To avoid having to make many changes to my original classes, I am backing up the database file (using copyFile) at the start of each test, clearing it/inserting the right values, and then restoring the backed-up db file after the test is done.

0

精彩评论

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

关注公众号