How do I know if my app is running with Robolectric?

允我心安 提交于 2019-11-27 06:39:23

问题


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?


回答1:


This is what works well for me on Robolectric 3.

public static boolean isRoboUnitTest() {
    return "robolectric".equals(Build.FINGERPRINT);
}



回答2:


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 :)




回答3:


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.



来源:https://stackoverflow.com/questions/28321961/how-do-i-know-if-my-app-is-running-with-robolectric

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!