7

I was trying to test this function

  UserApi createUserApi(String url, String username, String password) {
    UserApi userApi = new UserApi(base: route(url), serializers: repo);
    userApi.base.basicAuth('$username', '$password');
    return userApi;
  }

basically, the test was to compare the result of this function with a "manually composition" of it, expecting to have the same result. But It doesn't:

  String username = "asd";
  String password = "asd";
  UserApi userApiTest = new UserApi(base: route("asd"), serializers: repo);
  userApiTest.base.basicAuth('$username', '$password');
  test("UserApi creation", () {
    UserApi userApi = _presenter.createUserApi("asd", "asd", "asd");
    expect(userApi, userApiTest);
  }); 

The result is always :

Expected: <Instance of 'UserApi'>
  Actual: <Instance of 'UserApi'>

Why are they different? In the debug every property is the same.

1 Answer 1

8

You have two different instances of UserApi. Them having the same property values does not make them equal.

You would need to implement hashCode and operator==. By default only comparing the references to the same instance of an object are considered equal (because they are identical)

See also

Sign up to request clarification or add additional context in comments.

7 Comments

Sorry, if I ask a stupid question, but so I should override the == method in the class that I want to test?
If you want meaningful results for == with instances of your custom classes, then yes, you need to override operator == and hashCode.
expect(userApi, userApiTest); is executed as expect(userApi, equals(userApiTest)); which uses == to check equality. So your test is fine besides the missing operator == and get hashCode => ...
yes, I've just tried. I had also some other problems, but now it works. Thank you a lot!
Thats really sad that a new language has to do all this ugly code manually to simple compare 2 objects. Any modern language allows to compare objects.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.