How do I know if my app is running with Robolectri

2019-01-19 11:29发布

I have an android app that uses ORMLite/SQLite and I use Robolectric in conjunction with JUnit 4 to allow me to run unit tests in Android Studio and on a Jenkins build server.

Typically I would setup test data in my tests, in the setup, and then run my test scenarios against it but when I tried to do this I started getting issues and exceptions which seemed to be related to files being locked or something and that seems to be a problem others have had... so what I have done up until now is use the create database method in my database helper to create some dummy data which the tests expect to be there.

The problem is my application now needs to plug into a real database and I can't have it setup dummy data when it runs.

If there a way, within my database helper class, to detect if the code is executing on a device or within Robolectric?

3条回答
The star\"
2楼-- · 2019-01-19 11:43

This is what works well for me on Robolectric 3.

public static boolean isRoboUnitTest() {
    return "robolectric".equals(Build.FINGERPRINT);
}
查看更多
干净又极端
3楼-- · 2019-01-19 11:52

At some point you have to init OrmLiteSqliteOpenHelper with your Context.

Let assume you do this in your application class in onCreate. So just create Test<your application class name> in your tests sources and override onCreate with empty implementation.

Robolectric will find this class and will use during the tests. More details here.

查看更多
叛逆
4楼-- · 2019-01-19 11:55

To start with, I'll say that you shouldn't be putting code to initialise dummy/test data in the normal releasable code and in general you shouldn't need to know from the main app if you're in a robo run or not.

Now moving past the disclaimer and to actually answer your question... One way you could to this is to have a method in your application class like this

public boolean isRoboTestRun() {
    return false;
}

Then create a "TestApplication" in the test package that extends your normal application and overrides this method to return true. It's hacky, but that's because it's not really meant to work that way :)

查看更多
登录 后发表回答