I have written code to make screenshots on Android and I am trying to write a test for this. When running the test method, then I receive the following error message: Activity never becomes requested state "[STARTED, CREATED, DESTROYED, RESUMED]" (last lifecycle transition = "PRE_ON_CREATE")
. I have a hard time figuring out what I am doing wrong.
The production code has been tested manually.
My test code in src/androidTest/java/org/app
:
@RunWith (AndroidJUnit4.class)
public class ScreenshotsCaptorTest {
@Rule
public ActivityScenarioRule<TestActivity> rule =
new ActivityScenarioRule<>(TestActivity.class);
@Test
public void test() {
// This line is never reached
ActivityScenario<TestActivity> scenario = rule.getScenario();
scenario.onActivity(activity -> {
activity.setCallback(() -> {
try {
Bitmap screenshot = ScreenshotsCaptorBuilder.captor.takeScreenshot();
// Assert screenshot is non-null
} catch (CaptureScreenshotFailedException e) {
throw new RuntimeException(e);
}
});
Intent intent = ScreenshotsCaptorBuilder.intent(activity);
activity.startActivityForResult(intent, 100);
});
}
}
My helper Activity in src/androidTest/java/org/app
:
import org.app.test.R;
public class TestActivity extends Activity {
private Callback callback;
@Override
public void onCreate(Bundle savedInstanceState) {
// This line is never reached
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
}
public void setCallback(Callback callback) {
// This line is never reached
this.callback = callback;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
// This line is never reached
ScreenshotsCaptorBuilder.createCaptor(this, resultCode, intent);
callback.done();
}
public interface Callback {
// This line is never reached
void done();
}
}
The src/androidTest/AndroidManifest.xml
file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.app">
<application>
<activity
android:name=".TestActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
And src/androidTest/res/layout/activity_test.xml
:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.constraintlayout.widget.ConstraintLayout>
It would be really helpful if someone provide me some suggestions or tips to resolve my issue. Thanks in advance.