In appcenter failed unit test specifies only function name and line number - android

Edit, probably the better place to have posted this is on the appcenter forums (which I have now done):
https://github.com/microsoft/appcenter-cli/issues/1137
In short, an app I'm working on is built in appcenter and set to run unit tests, the problem I have though is that I'm unable to figure out what is making them fail (they won't fail locally).
I can't share the code that I'm having trouble with here, but to illustrate the problem I'm having, Suppose I defined the following kotlin function:
fun returnFooString() {
return "Foo "
}
and wrote the following test:
#Test
fun test_returnFooString_returns_foo() {
val foo = returnFooString()
assertThat("${foo} is equal to "Foo", "Foo", foo)
}
What I'd like to see is something like:
java.lang.AssertionError: Foo is equal to Foo
Expected: "Foo"
but: was "Foo "
Expected :Foo
Actual :Foo
However the only thing I would see in the appcenter logs for this failing test is:
com.mypackage.name.MyTest > test_returnFooString_returns_foo FAILED
java.lang.AssertionError at MyTest.kt:4
and so I have no clue what just happened. I'm still somewhat of a beginner to android development, and though I've searched google, I haven't been successful in finding something that looks relevant. Is there some setting that can be placed in the build.gradle to not suppress the assertion message, or some environment variable(s) I need to specify in appcenter, or something else to see what was expected and received?
Right now I'm seeing if I can throw exceptions in the test / code to shed some light on the issue but there must be a nicer way (especially since it takes about 10 minutes for a build)
Edit: throwing exceptions doesn't work, if I throw an exception logging out every variable I'm interested in, all I get back is something like:
com.mypackage.name.MyTest > test_returnFooString_returns_foo FAILED
java.lang.Exception at MyTest.kt:4
At this point it seems I either have to abandon the tests or do something crazy like writing 256 tests to figure out the first character my string has at position 0, then 10 minutes later another 256 to figure out the second ...

I turns out that logging can be enabled with the following:
testOptions {
unitTests.all {
testLogging {
showStandardStreams true
}
}
}

Related

Unit test can not be achieved in android studio using kotlin

In android studio using kotlin, I created a class with the code below:
class Dice(val numSides:Int){
fun roll():Int{
return (1..numSides).random()
}
}
in ExampleUnitTest.kt file I have created the following code to test:
class ExampleUnitTest {
#Test
fun generates_number() {
val dice = Dice(4)
val rollResult = dice.roll()
assertTrue("The value of rollResult was not between 1 and 6", rollResult in 1..6)
}
}
The test should be passed only if Dice(6) as the result should be any number between 1 to 6 but as shown above when with Dice(4) or any number, the test passed. that why? thanks
Your test checks if the rolled number is between 1 and 6. With Dice(4) the result will be between 1 and 4, which means it's always going to be between 1 and 6 as well. Or to put it another way, it's impossible for you to get a value from Dice(4).roll() that isn't somewhere between 1 and 6 - it's never going to be 5 or 6, but that doesn't contradict anything!
What you probably want to test is whether Dice(4).roll()'s possible range of outputs is from 1 to 6. But there's no way to absolutely prove that from the outside, not the way the class is written anyway. All you can do is provide a value for numSides and then call roll() and check the output. That's all the class offers to you in terms of interactivity.
A better question is why you want to test this? Your test seems to be written to fail when your code is working - you should be testing that the behaviour is what you'd expect, so all your tests pass. So really, what you'd want to test is that Dice(4).roll() only produces values within the expected range, i.e. between 1 and 4.
Since it's random the only way to really do this is run the same test lots of times and make sure a bad number never comes up (or you eventually see a number you want), so you can say with a high degree of confidence that it's probably correct. Something like
#Test
fun generates_number() {
val dice = Dice(4)
val allGood = generateSequence { dice.roll() }.take(9999).all { it in 1..4 }
assertTrue("At least one dice roll was not between 1 and 4", allGood)
}
(or you could use a for loop with break to exit early if one of the values isn't valid, instead of the sequence + all)
I just picked 9999 at random but you could use statistics to pick a more suitable number. But the problem here is the random behaviour - because it's not predictable, you can't do a simple state in -> result out test with an expected result.

How to conditionally skip a unit test in Android and kotlin?

I need to run a unit test based on whether this asset exists at runtime. The reason is, I am downloading the file in react native and in android, I am running some unit tests that requires this file.
I would like to run the unit test only if this file exists. Does anyone have any suggestions or code samples on how this can be achieved? Or is there another way these unit tests can be accomplished?
You shouldn't do that in a unit test because you want to have the file locally in your testing environment or have a mock that provides it. Otherwise you're not Eradicating Non-Determinism in Tests.
Let's assume you need to do something like that anyway. So, I would add a condition in the assert expression:
#Test
fun `Given a variable When has a value Then assert it has a value`(){
var myVar = null
myVar = getAValue()
myVar?.let {
assertNotEquals(null, myVar)
}
}
To me, eradicating non determinism in this particular context means that test scope has always specific expected values, the conditional expression in the let or an if enclosing an assert expression violates that. Hence the code above shouldn't be part of your tests. Instead, you have to write a test for the case myVar is null, you write another test for the case myVar is non null.
That's why I use Given, When, Then the conditional state would make the Given/When very messy.

How to force Jacoco to use a specific version in Gradle

Based on the release notes in version 0.8.3 the not-null assertion operator is filtered out, I'm using Jacoco version 0.8.5 like this:
jacoco {
toolVersion = "0.8.5"
}
But it's telling me that Not covered by tests (8 conditions)
I'm using com.dicedmelon.gradle:jacoco-android Github link
I think toolVersion = "0.8.5" not working or something like that, so for that I need a way to force Jacoco version.
Is there any way to fix this issue?
Without seeing your code and your tests I can't say with 100% confidence but it looks like Jacoco is working fine and there are cases not covered there.
You're using the !! 3 times. When you use this operator, in reality, you're creating 2 flows, for when the variable is null and another for not-null. If you add tests for the cases where the variables are null, you should reach 100% coverage.
Just to make explicit, if you would handle your nullable with safe calls, you would have something like this:
val token = authResult.user?.let {
authenticationDataSource.getIdToken(true, it)
?.let { it.token }
?: throw GetIdTokenResultIsNullException()
} ?: throw UserIsNullException()
token?.let {
authenticationDataSource.loginBy(AuthenticationPayload(it))
} ?: throw TokenIsNullException()
Wherever, I'm throwing exceptions you should handle that case as desired, and this is the alternate branch that is created by the nullability.
If you're sure that your values won't be null then you should change your types to make it clear and avoid extra checks.
On a side note, jacoco-android doesn't seem to be maintained anymore here and it's not compatible with newer gradle versions, so I would recommend using Jacoco directly. Migrating from jacoco-android to jacoco shouldn't be that hard.

Google App Script Error : "The script completed but did not return anything." [duplicate]

The Q&A is currently a subject of meta discussion, do participate. The current plan is to split where possible into Q&As. Answers to the A&A are community wiki and the question should become one when the status is resolved.
Preface
This Q&A strives to become a collection and a reference target for common errors encountered during development in Google Apps Script language in hopes to improve long-term maintainability of google-apps-script tag.
There are several similar and successful undergoings in other languages and general-purpose tags (see c++, android, php, php again), and this one follows suit.
Why it exists?
The amount of questions from both new and experienced developers regarding the meaning and solutions to errors encountered during development and production that can be effectively reduced to a single answer is substantial. At the time of writing, even running a query only by language tag yields:
"Cannot find method" 8 pages
"Cannot read property" 9 pages
"Cannot call ... in this context" 5 pages
"You do not have permission" 11 pages
Linking to a most relevant duplicate is hard and time-consuming for volunteers due to the need to consider nuances and often poorly-worded titles.
What it consists of?
Entries in this Q&A contain are designed to provide info on how to:
parse the error message structure
understand what the error entails
consistently reproduce (where applicable)
resolve the issue
provide a link to canonical Q&A (where possible)
Table of Contents
To help you navigate the growing reference please use the TOC below:
General errors
Service-specific errors
What this is not?
The scope of the Q&A is limited to common (not trivial). This is not:
a catch-all guide or "best practices" collection
a reference for general ECMAScript errors
GAS documentation
a resources list (we have a tag wiki for that)
What to add?
When adding an entry, please, consider the following:
is the error common enough (see "why" section for examples)?
can the solution be described concisely and be applicable for most cases?
Preface
The answer provides a guide on general errors that can be encountered when working with any Google service (both built-in and advanced) or API. For errors specific to certain services, see the other answer.
Back to reference
General errors
Message
TypeError: Cannot read property 'property name here' from undefined (or null)
Description
The error message indicates that you are trying to access a property on an Object instance, but during runtime the value actually held by a variable is a special data type undefined. Typically, the error occurs when accessing nested properties of an object.
A variation of this error with a numeric value in place of property name indicates that an instance of Array was expected. As arrays in JavaScript are objects, everything mentioned here is true about them as well.
There is a special case of dynamically constructed objects such as event objects that are only available in specific contexts like making an HTTP request to the app or invoking a function via time or event-based trigger.
The error is a TypeError because an "object" is expected, but "undefined" is received
How to fix
Using default values
Logical OR || operator in JavaScript has an intersting property of evaluating the right-hand side iff the left-hand is falsy. Since objects in JS are truthy, and undefined and null are falsy, an expression like (myVar || {}).myProp [(myVar || [])[index] for arrays] will guarantee that no error is thrown and the property is at least undefined.
One can also provide default values: (myVar || { myProp : 2 }) guarantees accessing myProp to return 2 by default. Same goes for arrays: (myVar || [1,2,3]).
Checking for type
Especially true for the special case, typeof operator combined with an if statement and a comparison operator will either allow a function to run outside of its designated context (i.e. for debugging purposes) or introduce branching logic depending on whether the object is present or not.
One can control how strict the check should be:
lax ("not undefined"): if(typeof myVar !== "undefined") { //do something; }
strict ("proper objects only"): if(typeof myVar === "object" && myVar) { //do stuff }
Related Q&As
Parsing order of the GAS project as the source of the issue
Message
Cannot convert some value to data type
Description
The error is thrown due to passing an argument of different type than a method expects. A common mistake that causes the error is accidental coercion of a number to string.
How to reproduce
function testConversionError() {
const ss = SpreadsheetApp.getActiveSheet();
ss.getRange("42.0",1);
}
How to fix
Make sure that the value referenced in the error message is of data type required by documentation and convert as needed.
Message
Cannot call Service and method name from this context
Description
This error happens on a context mismatch and is specific to container-bound scripts.
The primary use case that results in the error is trying to call a method only available in one document type (usually, getUi() as it is shared by several services) from another (i.e. DocumentApp.getUi() from a spreadsheet).
A secondary, but also prominent case is a result of calling a service not explicitly allowed to be called from a custom function (usually a function marked by special JSDoc-style comment #customfunction and used as a formula).
How to reproduce
For bound script context mismatch, declare and run this function in a script project tied to Google Sheets (or anything other than Google Docs):
function testContextMismatch() {
const doc = DocumentApp.getUi();
}
Note that calling a DocumentApp.getActiveDocument() will simply result in null on mismatch, and the execution will succeed.
For custom functions, use the function declared below in any cell as a formula:
/**
* #customfunction
*/
function testConversionError() {
const ui = SpreadsheetApp.getUi();
ui.alert(`UI is out of scope of custom function`);
}
How to fix
Context mismatch is easily fixed by changing the service on which the method is called.
Custom functions cannot be made to call these services, use custom menus or dialogs.
Message
Cannot find method Method name here
The parameters param names do not match the method signature for method name
Description
This error has a notoriously confusing message for newcomers. What it says is that a type mismatch occurred in one or more of the arguments passed when the method in question was called.
There is no method with the signature that corresponds to how you called it, hence "not found"
How to fix
The only fix here is to read the documentation carefully and check if order and inferred type of parameters are correct (using a good IDE with autocomplete will help). Sometimes, though, the issue happens because one expects the value to be of a certain type while at runtime it is of another. There are several tips for preventing such issues:
Setting up type guards (typeof myVar === "string" and similar).
Adding a validator to fix the type dynamically thanks to JavaScript being dynamically typed.
Sample
/**
* #summary pure arg validator boilerplate
* #param {function (any) : any}
* #param {...any} args
* #returns {any[]}
*/
const validate = (guard, ...args) => args.map(guard);
const functionWithValidator = (...args) => {
const guard = (arg) => typeof arg !== "number" ? parseInt(arg) : arg;
const [a,b,c] = validate(guard, ...args);
const asObject = { a, b, c };
console.log(asObject);
return asObject;
};
//driver IIFE
(() => {
functionWithValidator("1 apple",2,"0x5");
})()
Messages
You do not have permission to perform that action
The script does not have permission to perform that action
Description
The error indicates that one of the APIs or services accessed lacks sufficient permissions from the user. Every service method that has an authorization section in its documentation requires at least one of the scopes to be authorized.
As GAS essentially wraps around Google APIs for development convenience, most of the scopes listed in OAuth 2.0 scopes for APIs reference can be used, although if one is listed in the corresponding docs it may be better to use it as there are some inconsistencies.
Note that custom functions run without authorization. Calling a function from a Google sheet cell is the most common cause of this error.
How to fix
If a function calling the service is ran from the script editor, you are automatically prompted to authorize it with relevant scopes. Albeit useful for quick manual tests, it is best practice to set scopes explicitly in application manifest (appscript.json). Besides, automatic scopes are usually too broad to pass the review if one intends to publish the app.
The field oauthScopes in manifest file (View -> Show manifest file if in code editor) should look something like this:
"oauthScopes": [
"https://www.googleapis.com/auth/script.container.ui",
"https://www.googleapis.com/auth/userinfo.email",
//etc
]
For custom functions, you can fix it by switching to calling the function from a menu or a button as custom functions cannot be authorized.
For those developing editor Add-ons, this error means an unhandled authorization lifecycle mode: one has to abort before calls to services that require authorization in case auth mode is AuthMode.NONE.
Related causes and solutions
#OnlyCurrentDoc limiting script access scope
Scopes autodetection
Message
ReferenceError: service name is not defined
Description
The most common cause is using an advanced service without enabling it. When such a service is enabled, a variable under the specified identifier is attached to global scope that the developer can reference directly. Thus, when a disabled service is referenced, a ReferenceError is thrown.
How to fix
Go to "Resources -> Advanced Google Services" menu and enable the service referenced. Note that the identifier should equal the global variable referenced.
For a more detailed explanation, read the official guide.
If one hasn't referenced any advanced services then the error points to an undeclared variable being referenced.
Message
The script completed but did not return anything.
Script function not found: doGet or doPost
Description
This is not an error per se (as the HTTP response code returned is 200 and the execution is marked as successful, but is commonly regarded as one. The message appears when trying to make a request/access from browser a script deployed as a Web App.
There are two primary reasons why this would happen:
There is no doGet or doPost trigger function
Triggers above do not return an HtmlOutput or TextOutput instance
How to fix
For the first reason, simply provide a doGet or doPost trigger (or both) function. For the second, make sure that all routes of your app end with creation of TextOutput or HtmlOutput:
//doGet returning HTML
function doGet(e) {
return HtmlService.createHtmlOutput("<p>Some text</p>");
}
//doPost returning text
function doPost(e) {
const { parameters } = e;
const echoed = JSON.stringify(parameters);
return ContentService.createTextOutput(echoed);
}
Note that there should be only one trigger function declared - treat them as entry points to your application.
If the trigger relies on parameter / parameters to route responses, make sure that the request URL is structured as "baseURL/exec?query" or "baseURL/dev?query" where query contains parameters to pass.
Related Q&As
Redeploying after declaring triggers
Message
We're sorry, a server error occurred. Please wait a bit and try again.
Description
This one is the most cryptic error and can occur at any point with nearly any service (although DriveApp usage is particularly susceptible to it). The error usually indicates a problem on Google's side that either goes away in a couple of hours/days or gets fixed in the process.
How to fix
There is no silver bullet for that one and usually, there is nothing you can do apart from filing an issue on the issue tracker or contacting support if you have a GSuite account. Before doing that one can try the following common remedies:
For bound scripts - creating a new document and copying over the existing project and data.
Switch to using an advanced Drive service (always remember to enable it first).
There might be a problem with a regular expression if the error points to a line with one.
Don't bash your head against this error - try locating affected code, file or star an issue and move on
Syntax error without apparent issues
This error is likely to be caused by using an ES6 syntax (for example, arrow functions) while using the deprecated Rhino runtime (at the time of writing the GAS platform uses V8).
How to fix
Open "appscript.json" manifest file and check if runtimeVersion is set to "V8", change it if not, or remove any ES6 features otherwise.
Quota-related errors
There are several errors related to quotas imposed on service usage. Google has a comprehensive list of those, but as a general rule of thumb, if a message matches "too many" pattern, you are likely to have exceeded the respective quota.
Most likely errors encountered:
Service invoked too many times: service name
There are too many scripts running
Service using too much computer time for one day
This script has too many triggers
How to fix
In most cases, the only fix is to wait until the quota is refreshed or switch to another account (unless the script is deployed as a Web App with permission to "run as me", in which case owner's quotas will be shared across all users).
To quote documentation at the time:
Daily quotas are refreshed at the end of a 24-hour window; the exact time of this refresh, however, varies between users.
Note that some services such as MailApp have methods like getRemainingDailyQuota that can check the remaining quota.
In the case of exceeding the maximum number of triggers one can check how many are installed via getProjectTriggers() (or check "My triggers" tab) and act accordingly to reduce the number (for example, by using deleteTrigger(trigger) to get rid of some).
Related canonical Q&As
How are daily limitations being applied and refreshed?
"Maximum execution time exceeded" problem
Optimizing service calls to reduce execution time
References
How to make error messages more meaningful
Debugging custom functions
Service-specific errors
The answer concerns built-in service-related errors. For general reference see the other answer. Entries addressing issues with services listed in official reference are welcome.
Back to reference
SpreadsheetApp
The number of rows in the range must be at least 1
This error is usually caused by calling the getRange method where the parameter that sets the number of rows happens to equal to 0. Be careful if you depend on getLastRow() call return value - only use it on non-empty sheets (getDataRange will be safer).
How to reproduce
sh.getRange(1, 1, 0, sh.getLastColumn()); //third param is the number of rows
How to fix
Adding a guard that prevents the value from ever becoming 0 should suffice. The pattern below defaults to the last row with data (optional if you only need a certain number of rows) and to 1 if that also fails:
//willFail is defined elsewhere
sh.getRange(1, 1, willFail || sh.getLastRow() || 1, sh.getLastColumn());
Error: “Reference does not exist”
The error happens when calling a custom function in a spreadsheet cell that does not return a value. The docs do mention only that one "must return a value to display", but the catch here is that an empty array is also not a valid return value (no elements to display).
How to reproduce
Call the custom function below in any Google Sheets spreadsheet cell:
/**
* #customfunction
*/
const testReferenceError = () => [];
How to fix
No specific handling is required, just make sure that length > 0.
The number of rows or cells in the data does not match the number of rows or cells in the range. The data has N but the range has M.
Description
The error points to a mismatch in dimensions of range in relation to values. Usually, the issue arises when using setValues() method when the matrix of values is smaller or bigger than the range.
How to reproduce
function testOutOfRange() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getActiveSheet();
const rng = sh.getActiveRange();
const vals = rng.getValues();
try {
vals.push([]);
rng.setValues(vals);
} catch (error) {
const ui = SpreadsheetApp.getUi();
ui.alert(error.message);
}
}
How to fix
If it is routinely expected for values to get out of bounds, implement a guard that catches such states, for example:
const checkBounds = (rng, values) => {
const targetRows = rng.getHeight();
const targetCols = rng.getWidth();
const { length } = values;
const [firstRow] = values;
return length === targetRows &&
firstRow.length === targetCols;
};
The coordinates of the range are outside the dimensions of the sheet.
Description
The error is a result of a collision between two issues:
The Range is out of bounds (getRange() does not throw on requesting a non-existent range)
Trying to call a method on a Range instance referring to a non-existent dimension of the sheet.
How to reproduce
function testOB() {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sh = ss.getActiveSheet();
const rng = sh.getRange(sh.getMaxRows() + 1, 1);
rng.insertCheckboxes();
}
How to fix
Check that number of rows (getMaxRow()) and columns (getMaxColumns()) are both greater or equal to the parameters passed to getRange() method call and change them accordingly.
Exception: You can't create a filter in a sheet that already has a filter.
Description
The message means that you are trying to call a createFilter method on a Range in a Sheet that already has a filter set (either via UI or script), thus violating the restriction on 1 filter per Sheet, to quote the documentation:
There can be at most one filter in a sheet.
How to reproduce
const testFilterExistsError = () => {
const sh = SpreadsheetApp.getActiveSheet();
const rng = sh.getDataRange();
const filter1 = rng.createFilter();
const filter2 = rng.createFilter();
};
How to fix
Add a guard that checks for the existence of the filter first. getFilter returns either a filter or null if called on a Range instance and is perfect for the job:
const testFilterGuard = () => {
const sh = SpreadsheetApp.getActiveSheet();
const rng = sh.getDataRange();
const filter = rng.getFilter() || rng.createFilter();
//do something useful;
};
UrlFetchApp
Attribute provided with no value: url
Description
The error is specific to UrlFetchApp service and happens when fetch or fetchAll method gets called with an empty string or non-string value.
How to reproduce
const response = UrlFetchApp.fetch("", {});
How to fix
Make sure that a string containing a URI (not necessarily valid) is passed to the method as its first argument. As its common root cause is accessing a non-existent property on an object or array, check whether your accessors return an actual value.

Espresso test passes individually, fails when run in the suite

I have the following Espresso test. It always passes if I run it by itself, but always fails when I run all the tests in the class together.
What's also a bit strange is that it used to work even as part of the suite. I'm not sure why now it stopped working. It must be something I've done but I don't know what.
#Test
public void itemHasImage_ShowsImage() {
closeSoftKeyboard();
if (mItem.getImageUrl() != null) {
onView(withId(R.id.edit_item_image)).perform(scrollTo())
.check(matches(isDisplayed()));
}
}
The error I'm getting is:
Error performing 'scroll to'...
...
Caused by: java.lang.RuntimeException: Action will not be performed
because the target view does not match one or more of the following
constraints:(view has effective visibility=VISIBLE and is descendant
of a: (is assignable from class: class android.widget.ScrollView...
The view is visible and a descendant of a scroll view, as evidenced by it passing when run on it's own.
When it gets to this test (in the suite) it just doesn't scroll. But when I run it by itself it scrolls just fine.
In another stack overflow question I asked recently Espresso not starting Activity the same for second iteration in parameterised test, I found out that onDestroy from the previous test was getting called after onResume in the current test, causing it to set a value to null and fail the test. Again in that situation, the problem was that the test passed by itself but not in the suite. I now have a similar problem but no obvious way to fix it. (Edit: the workaround for the other question can no longer be applied).
Any ideas anyone? Could it be reading the wrong Activity somehow? Like maybe it's looking at the one from the previous test. That sounds ridiculous but after that last problem I had it seems possible.
Edit: Ok it turns out that when running this test as part of the suite, the image is in fact not visible causing the test to fail. I found this using the debugger and scrolling the view manually. But why?
I think it's a bug and have logged an issue here:
https://code.google.com/p/android/issues/detail?id=235247
It can able to solve using Orchestrator android testing utility library, It will executing each test case independently, so there is no chance of breaking in test suite
When using AndroidJUnitRunner version 1.0 or higher, you have access to a tool called Android Test Orchestrator, which allows you to run each of your app's tests within its own invocation of Instrumentation.
Enabling using build.gradle
android {
defaultConfig {
...
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
testOptions {
execution 'ANDROID_TEST_ORCHESTRATOR'
}
}
dependencies {
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestUtil 'com.android.support.test:orchestrator:1.0.1'
}
For more info:https://developer.android.com/training/testing/junit-runner.html#using-android-test-orchestrator
I had a similar issue but the cause was different, #Rakshith-Kumar suggestion of using Orchestrator might work, also putting each test method in a TestSuite could also be a solution, since the flakiness could be addressed by running each test individually.
Also want to mention that if you're testing component that's using RxJava schedulers (io scheduler for example) to run some tasks in a background thread, the flakiness could happen because Espresso will not be able to synchronize with the background threads.
A solution can be injecting a the ObservableTransformer to do the subscribeOn and observeOn operations. And for Espresso tests substitute the ObservableTransformer instance with another one that uses Schedulers.from(AsyncTask.THREAD_POOL_EXECUTOR) for the io scheduler.
Something like that:
public <T> ObservableTransformer<T, T> ioTransformer() {
return observable -> observable.subscribeOn(AsyncTask.THREAD_POOL_EXECUTOR).observeOn(AndroidSchedulers.mainThread());
}
This way Espresso can synchronize with background threads and avoid flakiness.
More info:
https://blog.danlew.net/2015/03/02/dont-break-the-chain/
https://developer.android.com/training/testing/espresso/#sync

Categories

Resources