felangel / mocktail

A mock library for Dart inspired by mockito
https://pub.dev/packages/mocktail
MIT License
588 stars 80 forks source link

[Question] Verify constructor #216

Closed fernando-s97 closed 2 months ago

fernando-s97 commented 8 months ago

I have a class A that has a method b().

The method B creates the object C with some specific args and execute the d() method.

So A().b() calls C(specific args).d().

The signature of B and D methods are the same. A only exists to create C with those specifics Args. So it's kind of a proxy in order to be aligned to DRY and not call C(specific args) multiple times in different places + be more semantic. B is a generic name and D is a better name for my specific use case.

I already have all the tests written for A and B, but since C.d is a proxy to A.b that only specifies custom logic to the constructor, I don't want to retest everything again. I only want to make sure C was called with the correct arguments.

How could I do this?

pastre commented 4 months ago

Can't you invert the dependency and inject a factory that makes C into A? you could then unit test against the factory AND that A().b() calls the factory separately

renancaraujo commented 4 months ago

You can also make de C constructor overridable within A:

class A {
  A({
    @visibleForTesting C Function()? testCConstructor
  }) : _cConstructor = testCConstructor ?? C.new;
}

And pass testCConstructor on your testing returning a Mocked C and verify D usage.