[英]How do I get the context and activity of MainActivity in JUnit test cases in android?
I am creating a simple quiz application where the user answers five questions and a result is toasted onto the screen. 我正在创建一个简单的测验应用程序,其中用户回答了五个问题,并将结果烘烤到了屏幕上。 In my MainActivity, I call the constructor of a questionsMethods class with parameters context and activity. 在我的MainActivity中,我调用带有参数上下文和活动的questionsMethods类的构造函数。
My question is: How do I get the context and activity of MainActivity in a JUnit test class? 我的问题是:如何在JUnit测试类中获取MainActivity的上下文和活动? I need this because the methods in questionsMethods make use of context and activity. 我需要这样做是因为questionsMethods中的方法利用了上下文和活动。
Part of the code: MainActivity: 部分代码:MainActivity:
public class MainActivity extends AppCompatActivity {
questionsMethods myQuestionMethods = new questionsMethods(this, this);
private String[] questionArray = new String[30]; // Holds text file
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AssetManager assetManager = getAssets();
myQuestionMethods.readWriteFile("listofquestions.txt", questionArray); // Reads from text file into array
questionsMethods: questionsMethods:
public class questionsMethods {
private Context mContext;
private Activity mActivity;
private int localCounterForCurrQuestionCount = 1;
private String[] localQuestionsArray = new String[30];
public questionsMethods(Context context, Activity activity) {
mContext = context;
mActivity = activity;
}
public void readWriteFile(String fileName, String[] questionArray) {
int count = 0; // Holds count of array index in which a line is stored
try {
String nextLine;
InputStream is = mContext.getAssets().open(fileName); // Retrieves and opens fileName
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
while ((nextLine = bufferedReader.readLine()) != null) { // Check if line incrementer reaches the end
questionArray[count] = nextLine;
count++;
}
} catch (java.io.IOException ex) {
Log.i("Error", "Cannot read file");
System.exit(1);
}
localQuestionsArray = questionArray;
}
Use Robolectric, however your code is very hard to test. 使用Robolectric,但是您的代码很难测试。 The QuestionMethods
class is only responsible for business logic and should not depend on Android. QuestionMethods
类仅负责业务逻辑,不应依赖于Android。
So if you want to make your code cleaner and you want to test QuestionMethods
properly, Robolectric should not be used for classes that are responsible for business logic. 因此,如果您想使代码更整洁并且要正确测试QuestionMethods
,则Robolectric不应用于负责业务逻辑的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.