s-hunter
s-hunter

Reputation: 25836

How to assert two list of string using RxJava TestObserver?

In this test, those two lists of strings are the same, but the assertValue method is telling me they are not equal because they have different memory addresses. How can I make it test against the actual strings in the array, so the following will pass?

@Test
public void shouldReturnStringList() {;
    String[] strings = {"Hello", "World"};
    String[] strings2 = {"Hello", "World"};
    Observable<String[]> stringsObservable = Observable.just(strings);

    TestObserver<String[]> testObserver = new TestObserver<>();
    stringsObservable.subscribe(testObserver);

    testObserver.assertValue(strings2);
}

The failed test message:

java.lang.AssertionError: Expected: [Ljava.lang.String;@5ebec15 (class: String[]), Actual: [Ljava.lang.String;@21bcffb5 (class: String[]) (latch = 0, values = 1, errors = 0, completions = 1)

Upvotes: 4

Views: 2776

Answers (1)

Kiskae
Kiskae

Reputation: 25603

Since assertValue uses basic Object.equals for its comparison, it will fail for arrays because they just compare addresses, not values.

You will need to use the assertValue(Predicate<T>) version of the operator and then use Arrays.equals(Object[],Object[]) to do the actual comparison:

testObserver.assertValue(arr -> Arrays.equals(arr, strings2))

Upvotes: 10

Related Questions