How do I test Jobs created with Android-Job library? Any ideas on unit testing, instrumented testing or even manual testing are appreciated, I just want to check if it works as expected.
To be specific, I have a job that performs an HTTP request every N hours:
package com.kondenko.yamblzweather.job;
import android.support.annotation.NonNull;
import com.evernote.android.job.Job;
import com.evernote.android.job.JobRequest;
import com.kondenko.yamblzweather.model.entity.WeatherData;
import com.kondenko.yamblzweather.ui.weather.WeatherInteractor;
import com.kondenko.yamblzweather.utils.SettingsManager;
import java.util.concurrent.TimeUnit;
import javax.inject.Inject;
public class UpdateWeatherJob extends Job {
private WeatherInteractor interactor;
private String cityId;
private String units;
private long refreshRateHr;
// Do not delete, needed for job creation
public static final String TAG = "UpdateWeaterJob";
#Inject
public UpdateWeatherJob(WeatherInteractor interactor, SettingsManager settingsManager) {
this.interactor = interactor;
this.cityId = settingsManager.getSelectedCity();
this.units = settingsManager.getSelectedUnitValue();
this.refreshRateHr = settingsManager.getRefreshRate();
}
#NonNull
#Override
protected Result onRunJob(Params params) {
WeatherData data = interactor.getWeather(cityId, units).blockingGet();
return data != null ? Result.SUCCESS : Result.FAILURE;
}
public void buildJobRequest(String name) {
new JobRequest.Builder(UpdateWeatherJob.TAG)
.setPeriodic(TimeUnit.HOURS.toMillis(refreshRateHr))
.setRequiredNetworkType(JobRequest.NetworkType.CONNECTED)
.setRequirementsEnforced(true)
.setPersisted(true)
.build()
.schedule();
}
}
We at Evernote test jobs the following way:
Unit tests -> We tend to extract the logic into actions, similar to presenters in a MVP setup. This removes Android dependencies and the actions are unit testable.
QA -> We have QA options to trigger jobs manually. This way our QA team can verify that the job produces the correct output
Verifying timing -> There we rely on the logs.
You also should take a look at these slides. ADB can be really helpful to verify curtain assumptions.
Related
I want to try out work manager for the first time. I am used to rxJava so I decided to implement my work manager using RxWorker. But the testing aspect is giving me headache.Basically, the work manager checks firebase to get latest changes to latest changes to particular document (This is not the best use case I know).But the problem is in the test returns without waiting for success or failure.It returns when the work manager is still running.
This is my work manager implementation
class MidiSyncWorker(context: Context, params: WorkerParameters) : RxWorker(context, params) {
override fun createWork(): Single<Result> {
return Injection.provideSharePrefsRepo.midiArchiveVersion()
.flatMapObservable { currentVersion ->
Injection.provideOnlineRepo.latestMidiArchive()
.filter { onlineMidi -> onlineMidi.version > currentVersion }
}.firstOrError()
.map { onlineMidi ->
val outputData = Data.Builder()
.putString(KEY_FIREBASE_ARCHIVE_PATH, onlineMidi.url)
Result.success(outputData.build()) }
}
.onErrorReturn { Result.failure() }
}
This is my test
fun midiSyncVersionCheck_success_onlineVersionDiffersFromLocalVersion() {
// create request
val request = OneTimeWorkRequestBuilder<MidiSyncWorker>()
.build()
wmRule.workManager.enqueue(request).result.get()
val workInfo = wmRule.workManager.getWorkInfoById(request.id).get(10, TimeUnit.SECONDS)
assertThat(workInfo.state, `is`(WorkInfo.State.SUCCEEDED))
}
I expected the test to wait until workmanager returns success or failure. But it returns while work manager is still running
java.lang.AssertionError:
Expected: is <SUCCEEDED>
but: was <RUNNING>
WorkManager makes available a couple of ways to test your Worker classes. You can find all the details on WorkManager Testing documentation page.
The original WorkManagerTestInitHelper only supports Worker classes, meanwhile, the newly introduce in (WorkManager v2.1.0-alpha01) TestListenableWorkerBuilder can be used to test both ListenableWorker classes and the other classes that derives from it (like CoroutineWorker and RxWorker.
In your particular case, you should be able to do:
import android.content.Context
import androidx.test.core.app.ApplicationProvider
import androidx.work.ListenableWorker.Result
import androidx.work.testing.TestListenableWorkerBuilder
import org.hamcrest.CoreMatchers.`is`
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
#RunWith(JUnit4::class)
class MyWorkTest {
private lateinit var context: Context
#Before
fun setup() {
context = ApplicationProvider.getApplicationContext()
}
#Test
fun testMidiSyncWorker() {
// Get the ListenableWorker
val worker = TestListenableWorkerBuilder<MidiSyncWorker>(context).build()
// Start the work synchronously
val result = worker.startWork().get()
assertThat(result, `is`(Result.success()))
}
}
In this way you're calling synchrously your worker class.
In this case you need to use the as a test dependency in your build.gradle file:
def work_version = "2.1.0-alpha02"
androidTestImplementation "androidx.work:work-testing:$work_version"
You can find a similar, complete, sample (for a CoroutineWorker), on the Kotlin's coroutine Codelab.
I'm trying to do some unit test on a basic Android app. it just do a login to some WS using retrofit my app has a MVP pattern.
What I'm doing?
call to presenter layer this will call to interactor and here I will call to my service
#Override
public void doLogin(String user, String pwd, final LoginListener loginListener) {
try {
final LoginRequest request = new LoginRequest();
request.setEmpleado(user);
request.setPwd(pwd);
Callback<LoginResponse> callback = new Callback<LoginResponse>() {
#Override
public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) {
if(response != null && response.isSuccessful() && response.body() != null) {
if("00".equals(response.body().getCodigo())) {
loginListener.authOK();
} else {
loginListener.showError();
}
} else {
loginListener.showError();
}
}
#Override
public void onFailure(Call<LoginResponse> call, Throwable t) {
"+t.getMessage()+" "+t.getCause());
if(t instanceof SocketTimeoutException) {
loginListener.showError();
} else {
loginListener.showError();
}
}
};
WSLogin wsLogin = RetrofitClient.getInstance().getRetrofit().create(WSLogin.class);
wsLogin.autenticar(request).enqueue(callback);
} catch (Exception e) {
loginListener.showError();
e.printStackTrace();
}
My service it's called but i never get into callback
Test
package com.arleckk.loginmvpci.login;
import com.arleckk.loginmvpci.login.presenter.LoginListener;
import com.arleckk.loginmvpci.login.presenter.LoginPresenter;
import com.arleckk.loginmvpci.login.presenter.LoginPresenterImpl;
import com.arleckk.loginmvpci.login.view.LoginView;
import com.arleckk.loginmvpci.model.LoginResponse;
import com.arleckk.loginmvpci.network.WSLogin;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.mockito.junit.MockitoJUnitRunner;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Response;
import static org.junit.Assert.assertEquals;
#RunWith(PowerMockRunner.class)
#PowerMockIgnore("javax.net.ssl.*")
public class LoginTest {
#Mock private LoginView loginView;
#Mock private LoginPresenter loginPresenter;
#Mock private LoginListener loginListener;
#Mock private Call<LoginResponse> loginResponseCall;
Response<LoginResponse> loginResponseResponse;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
loginPresenter = new LoginPresenterImpl(loginView);
}
#Test
public void testOK() throws IOException {
loginPresenter.doLogin("TEST", "TEST1234");
}
}
Another question is: do am I really doing unit test? I mean unit test only test a "Unit" of the code.
I'm expecting a LoginResponse object and then compare it and if it is equals to "00" it's sucessful
No, you're not. For a few reasons. First off, you don't have a test here. You don't have a single assertion. No matter what happens your code will say pass. So it isn't a test. A test would be to say call doLogin with a working login, and ensure that loginListener.authOK() is called. Then another test that uses a bad password, and checks that showError is called. Without that all you have is a waste of time.
Second- this is horribly scoped for a unit test. For a unit test, you should be checking that the smallest unit of code works. Here, you're checking that your entire networking stack, and your server, all work. That's way too much. And a unit test should never depend on an outside server working, that will just lead to a flaky test- something like that should be in an integration suite.
Your code right now isn't optimized for testing. If it was- you wouldn't be creating the retrofit client via a singleton in the code. You'd pass it into doLogin. That way you could pass in a mock in a test that could return a fake response, and then test whether your code can correctly identify the a fake success and failure response correctly, removing the server dependency yet testing all of the functionality.
I cannot make liveData.postValue working in while trying to make unit test. I have been checking in google for a solution and this is the code I have now.
public class ProjectListViewModelTest {
GetProjectList getProjectList = Mockito.mock(GetProjectList.class);
ProjectModel.Project project = new ProjectModel.Project("testing",
"this is a test",
"https://logo.jpg",
new ProjectModel.Company("cat"),
"20150404",
"active");
List<ProjectModel.Project> projects = Arrays.asList(project);
ProjectModel.ProjectList projectsList = new ProjectModel.ProjectList(projects);
ProjectsListViewModel projectsListViewModel;
private PublishSubject<ProjectModel.ProjectList> projectsListPublishSubject = PublishSubject.create();
#Rule public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule();
#BeforeClass
public static void setUpRxSchedulers() {
Scheduler immediate = new Scheduler() {
#Override
public Disposable scheduleDirect(#NonNull Runnable run, long delay, #NonNull TimeUnit unit) {
return super.scheduleDirect(run, 0, unit);
}
#Override
public Scheduler.Worker createWorker() {
return new ExecutorScheduler.ExecutorWorker(Runnable::run);
}
};
RxJavaPlugins.setInitIoSchedulerHandler(scheduler -> immediate);
RxJavaPlugins.setInitComputationSchedulerHandler(scheduler -> immediate);
RxJavaPlugins.setInitNewThreadSchedulerHandler(scheduler -> immediate);
RxJavaPlugins.setInitSingleSchedulerHandler(scheduler -> immediate);
RxAndroidPlugins.setInitMainThreadSchedulerHandler(scheduler -> immediate);
}
#Before
#Throws(exceptionClasses = Exception.class)
public void setUp() {
MockitoAnnotations.initMocks(this);
projectsListViewModel = new ProjectsListViewModel(getProjectList);
when(getProjectList.execute()).thenReturn(projectsListPublishSubject.take(1).singleOrError());
}
#Test
public void testExecuteGetProjectsListSuccess() {
LiveData<List<ProjectModel.MapProject>> liveData = projectsListViewModel.getLiveData();
ProjectModel.MapProject expectedResult = new ProjectModel.MapProject(
"testing", "this is a test", "https://logo.jpg",
"cat", "2015-04-04", "active");
projectsListViewModel.getProjects();
projectsListPublishSubject.onNext(projectsList);
Assert.assertEquals(expectedResult, liveData.getValue().get(0));
}
#After
public void tearDownClass(){
RxAndroidPlugins.reset();
}
The code that I have in setUpRxSchedulers is mandatory in order to avoid the same error (Method getMainLooper in android.os.Looper not mocked) with Rx. But I cannot solve this error that I get when calling liveData.post(projectList). In all the forums that I checked they say that with #Rule public InstantTaskExecutorRule instantExecutorRule = new InstantTaskExecutorRule(); the problem should be solved. But is not my case.
I put here the viewmodel as well in case it can help:
public class ProjectsListViewModel extends ViewModel {
GetProjectList getProjectList;
MutableLiveData<List<ProjectModel.MapProject>> liveData = new MutableLiveData<>();
public ProjectsListViewModel(GetProjectList getProjectList){
this.getProjectList = getProjectList;
}
public LiveData<List<ProjectModel.MapProject>> getLiveData(){
return liveData;
}
public void getProjects(){
getProjectList.execute()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(ProjectModel.ProjectList::getProjects)
.toObservable().flatMapIterable(projects -> projects)
.map(project -> project.convertToMapProject()).toList()
.subscribe(projectsList ->
liveData.setValue(projectsList));
}
}
The usage of InstantTaskExecutorRule will actually solve this.
I think the issue is that in JUnit 5 the #Rule annotation doesn't seem to be supported anymore (as Extensions are now the way to go). The code will compile successfully, but the rule just won't be applied.
There are (at least) two solutions to this:
Use JUnit 4
Is definitely the quicker, may not be the best depending on how much you need JUnit 5.
This can be done just by changing the annotation of your setup method from #BeforeEach to #Before and by importing the #Test annotation from JUnit 4.
Here's how your imports should look like.
import org.junit.Before
import org.junit.Rule
import org.junit.Test
Implement a InstantTaskExecutorExtension
This is better if you care about using JUnit 5 :)
Here's an article that talks about how to implement precisely InstantTaskExecutorExtension.
Once that's done remember to apply it to your test class using the #ExtendWith(InstantTaskExecutorExtension::class) annotation instead of #Rule!
Whenever I run a simple JUnit test on Android studio, the tests always succeed no matter what..
I already hit Build Variant and this is under Unit Tests.
public class ECUserTests extends InstrumentationTestCase{
public void test() throws Exception{
final int expected = 1;
final int reality = 5;
assertEquals(expected, reality);
}
I added
testOptions {
unitTests.returnDefaultValues = true
}
To my build.gradle file and now this is something that clearly isn't true is returning as passed.
For the new unit test support, you don't need to inherit from InstrumentationTestCase, but you do need to annotate your test method.
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class ECUserTests {
#Test
public void test() {
final int expected = 1;
final int reality = 5;
assertEquals(expected, reality);
}
}
To run unit test, it's required to select "Unit test" in Test Artifact under Build Variants and Android Studio version must be >1.1
Would anyone know how to test for the appearance of a Toast message in android espresso? In robotium its easy & I used but started working in espresso but dont getting the exact command.
This slightly long statement works for me:
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.not;
....
onView(withText(R.string.TOAST_STRING)).inRoot(withDecorView(not(is(getActivity().getWindow().getDecorView())))).check(matches(isDisplayed()));
The accepted answer is a good one but didn't work for me. So I searched a bit and found this blog article.
This gave me an idea of how to do it and I updated the solution above.
First I implemented the ToastMatcher:
import android.os.IBinder;
import android.support.test.espresso.Root;
import android.view.WindowManager;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class ToastMatcher extends TypeSafeMatcher<Root> {
#Override
public void describeTo(Description description) {
description.appendText("is toast");
}
#Override
public boolean matchesSafely(Root root) {
int type = root.getWindowLayoutParams().get().type;
if (type == WindowManager.LayoutParams.TYPE_TOAST) {
IBinder windowToken = root.getDecorView().getWindowToken();
IBinder appToken = root.getDecorView().getApplicationWindowToken();
if (windowToken == appToken) {
// windowToken == appToken means this window isn't contained by any other windows.
// if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
return true;
}
}
return false;
}
}
Then I implemented my check methods like this:
public void isToastMessageDisplayed(int textId) {
onView(withText(textId)).inRoot(MobileViewMatchers.isToast()).check(matches(isDisplayed()));
}
MobileViewMatchers is a container for accessing the matchers. There I defined the static method isToast().
public static Matcher<Root> isToast() {
return new ToastMatcher();
}
This works like a charm for me.
First make sure to import:
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static android.support.test.espresso.matcher.RootMatchers.withDecorView;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
Inside your class you probably have a rule like this:
#Rule
public ActivityTestRule<MyNameActivity> activityTestRule =
new ActivityTestRule<>(MyNameActivity.class);
Inside your test:
MyNameActivity activity = activityTestRule.getActivity();
onView(withText(R.string.toast_text)).
inRoot(withDecorView(not(is(activity.getWindow().getDecorView())))).
check(matches(isDisplayed()));
This worked for me, and it was pretty easy to use.
If you're using the newest Android Testing Tools from Jetpack, you know, that ActivityTestRule is deprecated and you should use ActivityScenario or ActivityScenarioRule(which contains the first).
Prerequisites. Create decorView variable and assign it before tests;
#Rule
public ActivityScenarioRule<FeedActivity> activityScenarioRule = new ActivityScenarioRule<>(FeedActivity.class);
private View decorView;
#Before
public void setUp() {
activityScenarioRule.getScenario().onActivity(new ActivityScenario.ActivityAction<FeedActivity>() {
#Override
public void perform(FeedActivityactivity activity) {
decorView = activity.getWindow().getDecorView();
}
});
}
Test itself
#Test
public void given_when_thenShouldShowToast() {
String expectedWarning = getApplicationContext().getString(R.string.error_empty_list);
onView(withId(R.id.button))
.perform(click());
onView(withText(expectedWarning))
.inRoot(withDecorView(not(decorView)))// Here we use decorView
.check(matches(isDisplayed()));
}
getApplicationContext() can be taken from androidx.test.core.app.ApplicationProvider.getApplicationContext;
First create a cutom Toast Matcher which we can use in our test cases -
public class ToastMatcher extends TypeSafeMatcher<Root> {
#Override public void describeTo(Description description) {
description.appendText("is toast");
}
#Override public boolean matchesSafely(Root root) {
int type = root.getWindowLayoutParams().get().type;
if ((type == WindowManager.LayoutParams.TYPE_TOAST)) {
IBinder windowToken = root.getDecorView().getWindowToken();
IBinder appToken = root.getDecorView().getApplicationWindowToken();
if (windowToken == appToken) {
//means this window isn't contained by any other windows.
return true;
}
}
return false;
}
}
1. Test if the Toast Message is Displayed
onView(withText(R.string.mssage)).inRoot(new ToastMatcher())
.check(matches(isDisplayed()));
2. Test if the Toast Message is not Displayed
onView(withText(R.string.mssage)).inRoot(new ToastMatcher())
.check(matches(not(isDisplayed())));
3. Test id the Toast contains specific Text Message
onView(withText(R.string.mssage)).inRoot(new ToastMatcher())
.check(matches(withText("Invalid Name"));
Thanks,
Anuja
Note - this answer is from This POST.
Though the question has an accepted answer - which BTW does not work for me - I'd like to add my solution in Kotlin which I derived from Thomas R.'s answer:
package somepkg
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.Root
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.view.WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
import android.view.WindowManager.LayoutParams.TYPE_TOAST
import org.hamcrest.Description
import org.hamcrest.Matcher
import org.hamcrest.TypeSafeMatcher
/**
* This class allows to match Toast messages in tests with Espresso.
*
* Idea taken from: https://stackoverflow.com/a/33387980
*
* Usage in test class:
*
* import somepkg.ToastMatcher.Companion.onToast
*
* // To assert a toast does *not* pop up:
* onToast("text").check(doesNotExist())
* onToast(textId).check(doesNotExist())
*
* // To assert a toast does pop up:
* onToast("text").check(matches(isDisplayed()))
* onToast(textId).check(matches(isDisplayed()))
*/
class ToastMatcher(private val maxFailures: Int = DEFAULT_MAX_FAILURES) : TypeSafeMatcher<Root>() {
/** Restrict number of false results from matchesSafely to avoid endless loop */
private var failures = 0
override fun describeTo(description: Description) {
description.appendText("is toast")
}
public override fun matchesSafely(root: Root): Boolean {
val type = root.windowLayoutParams.get().type
#Suppress("DEPRECATION") // TYPE_TOAST is deprecated in favor of TYPE_APPLICATION_OVERLAY
if (type == TYPE_TOAST || type == TYPE_APPLICATION_OVERLAY) {
val windowToken = root.decorView.windowToken
val appToken = root.decorView.applicationWindowToken
if (windowToken === appToken) {
// windowToken == appToken means this window isn't contained by any other windows.
// if it was a window for an activity, it would have TYPE_BASE_APPLICATION.
return true
}
}
// Method is called again if false is returned which is useful because a toast may take some time to pop up. But for
// obvious reasons an infinite wait isn't of help. So false is only returned as often as maxFailures specifies.
return (++failures >= maxFailures)
}
companion object {
/** Default for maximum number of retries to wait for the toast to pop up */
private const val DEFAULT_MAX_FAILURES = 5
fun onToast(text: String, maxRetries: Int = DEFAULT_MAX_FAILURES) = onView(withText(text)).inRoot(isToast(maxRetries))!!
fun onToast(textId: Int, maxRetries: Int = DEFAULT_MAX_FAILURES) = onView(withText(textId)).inRoot(isToast(maxRetries))!!
fun isToast(maxRetries: Int = DEFAULT_MAX_FAILURES): Matcher<Root> {
return ToastMatcher(maxRetries)
}
}
}
I hope this will be of help for later readers - the usage is described in the comment.
I write my custom toast matcher:
import android.view.WindowManager
import androidx.test.espresso.Root
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
class ToastMatcher : TypeSafeMatcher<Root>() {
override fun describeTo(description: Description) {
description.appendText("is toast")
}
override fun matchesSafely(root: Root): Boolean {
val type = root.getWindowLayoutParams().get().type
if (type == WindowManager.LayoutParams.TYPE_TOAST) {
val windowToken = root.getDecorView().getWindowToken()
val appToken = root.getDecorView().getApplicationWindowToken()
if (windowToken === appToken) {
return true
}
}
return false
}
}
And use like this:
onView(withText(R.string.please_input_all_fields)).inRoot(ToastMatcher()).check(matches(isDisplayed()))
For kotlin, I had to use the apply extension function, and this worked for me.
1- declare your ToastMatcher class in the androidTest folder:
class ToastMatcher : TypeSafeMatcher<Root?>() {
override fun matchesSafely(item: Root?): Boolean {
val type: Int? = item?.windowLayoutParams?.get()?.type
if (type == WindowManager.LayoutParams.FIRST_APPLICATION_WINDOW) {
val windowToken: IBinder = item.decorView.windowToken
val appToken: IBinder = item.decorView.applicationWindowToken
if (windowToken === appToken) { // means this window isn't contained by any other windows.
return true
}
}
return false
}
override fun describeTo(description: Description?) {
description?.appendText("is toast")
}
}
2- Then you use like this to test that the toast message actually displays
onView(withText(R.string.invalid_phone_number))
.inRoot(ToastMatcher().apply {
matches(isDisplayed())
});
Attribution to ToastMatcher class:
/**
* Author: http://www.qaautomated.com/2016/01/how-to-test-toast-message-using-espresso.html
*/
I would say for toast messages first define your rule
#Rule
public ActivityTestRule<AuthActivity> activityTestRule =
new ActivityTestRule<>(AuthActivity.class);
then whatever toast message text you are looking for type it in between quotation
for example I used "Invalid email address"
onView(withText("Invalid email address"))
.inRoot(withDecorView(not(activityTestRule.getActivity().getWindow().getDecorView())))
.check(matches(isDisplayed()));
I would like to suggest an alternative method, especially if you need to check that particular toast is NOT displayed
The problem here that
onView(viewMatcher)
.inRoot(RootMatchers.isPlatformPopup())
.check(matches(not(isDisplayed())))
or
onView(viewMatcher)
.inRoot(RootMatchers.isPlatformPopup())
.check(doesNotExist())
or any other custom inRoot checks
are throwing NoMatchingRootException even before the code passes to check method
You may just catch the exception and complete the test but that's not a good option since throwing and catching NoMatchingRootException consumes a lot of time in a comparison with the default test case. Seems that Espresso is waiting for the Root for a while
For this case is suggest just to give up with espresso here and use UiAutomator for this assertion. The Espresso and UiAutomator frameworks could easily work together in one environment.
val device: UiDevice
get() = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
fun assertPopupIsNotDisplayed() {
device.waitForIdle()
assertFalse(device.hasObject(By.text(yourText))))
}
fun assertPopupIsDisplayed() {
device.waitForIdle()
assertTrue(device.hasObject(By.text(yourText))))
}
Using ActivityScenarioRule and Java
Some imports for the code
import android.view.View;
import androidx.test.ext.junit.rules.ActivityScenarioRule;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.matcher.RootMatchers.withDecorView;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static androidx.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.not;
1. Declare the rule
//Change YourActivity by the activity you are testing
#Rule
public ActivityScenarioRule<YourActivity> activityRule
= new ActivityScenarioRule<>(YourActivity.class);
2. Initialize the decor view
private View decorView;
#Before
public void loadDecorView() {
activityRule.getScenario().onActivity(
activity -> decorView = activity.getWindow().getDecorView()
);
}
3. Finally test it
#Test
public void testWithToasts() {
//Arrange and act code
//Modify toast_msg to your own string resource
onView(withText(R.string.toast_msg)).
inRoot(RootMatchers.withDecorView(not(decorView)))
.check(matches(isDisplayed()));
}
I'm pretty new to this, but I made a base class 'BaseTest' that has all of my actions (swiping, clicking, etc.) and verifications (checking text views for content, etc.).
protected fun verifyToastMessageWithText(text: String, activityTestRule: ActivityTestRule<*>) {
onView(withText(text)).inRoot(withDecorView(not(activityTestRule.activity.window.decorView))).check(matches(isDisplayed()))
}
protected fun verifyToastMessageWithStringResource(id: Int, activityTestRule: ActivityTestRule<*>) {
onView(withText(id)).inRoot(withDecorView(not(activityTestRule.activity.window.decorView))).check(matches(isDisplayed()))
}
this works for me
onView(withId(R.id.inputField)).check(matches(withText("Lalala")));
The way Toasts are implemented makes it possible to detect a toast has been displayed. However there is no way to see if a Toast has been requested, thru a call to show()) or to block between the period of time between show() and when the toast has become visible. This is opens up unresolvable timing issues (that you can only address thru sleep & hope).
If you really really want to verify this, here's a not-so-pretty alternative using Mockito and a test spy:
public interface Toaster {
public void showToast(Toast t);
private static class RealToaster {
#Override
public void showToast(Toast t) {
t.show();
}
public static Toaster makeToaster() {
return new RealToaster();
}
}
Then in your test
public void testMyThing() {
Toaster spyToaster = Mockito.spy(Toaster.makeToaster());
getActivity().setToaster(spyToaster);
onView(withId(R.button)).perform(click());
getInstrumentation().runOnMainSync(new Runnable() {
#Override
public void run() {
// must do this on the main thread because the matcher will be interrogating a view...
Mockito.verify(spyToaster).showToast(allOf(withDuration(Toast.LENGTH_SHORT), withView(withText("hello world"));
});
}
// create a matcher that calls getDuration() on the toast object
Matcher<Toast> withDuration(int)
// create a matcher that calls getView() and applies the given view matcher
Matcher<Toast> withView(Matcher<View> viewMatcher)
another answer regarding this
if(someToast == null)
someToast = Toast.makeText(this, "sdfdsf", Toast.LENGTH_LONG);
boolean isShown = someToast.getView().isShown();