6

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.

Little Monkey
  • 5,395
  • 14
  • 45
  • 83

1 Answers1

7

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • Sorry, if I ask a stupid question, but so I should override the == method in the class that I want to test? – Little Monkey Oct 02 '18 at 07:01
  • 1
    If you want meaningful results for `==` with instances of your custom classes, then yes, you need to override `operator ==` and `hashCode`. – Günter Zöchbauer Oct 02 '18 at 07:05
  • 1
    `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 => ...` – Günter Zöchbauer Oct 02 '18 at 07:14
  • 1
    yes, I've just tried. I had also some other problems, but now it works. Thank you a lot! – Little Monkey Oct 02 '18 at 07:51
  • 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. – Rodrigo Manguinho Jul 08 '20 at 14:12
  • No matter how you design a programming language there will always be advantages and disadvantages. This one is a disadvantage that you get when you design a strongly typed language that produces small and fast executables as it is mandatory for web and mobile. – Günter Zöchbauer Jul 08 '20 at 15:08
  • I also think that there is no point of overriding `operator ==` and `hashCode` just because of the tests. This can also have a side-effects in your "regular" code. Why don't you implement (or let your IDE implement) `toString` method in `UserApi` class, and then compare like this: `expect(userApi.toString(), userApiTest.toString);` ? Or just "manually" compare every `UserApi` property individually. – DamirR Aug 14 '21 at 18:27