mockito icon indicating copy to clipboard operation
mockito copied to clipboard

Make `throwOnMissingStub` the default (eventually)

Open matanlurey opened this issue 7 years ago • 7 comments

This is a candidate for Mockito 4, and entirely opt-in before Mockito 4.

Rationale: The following currently "just works" in Mockito 3:

class Cat {
  List<String> toys;
}

class MockCat extends Mock implements Cat {}

void main() {
  var cat = new MockCat();
  cat.toys;
}

This is problematic:

  • The default behavior for unimplemented methods returns null, instead of NSM.
  • If users add new APIs to a class they often forget to add when(...) cases for them.
  • If non-nullability ever becomes available, this is incorrect behavior.

My suggestion is to start with a global opt-in/out flag, i.e.:

void main() {
  // Any instance of `Mock` now throws instead of returning null.
  Mock.throwOnMissingStub = true;
}

matanlurey avatar Jul 11 '18 23:07 matanlurey

+1 I like it. I thought we implemented something like this before and it was rolled back...

srawlins avatar Jul 11 '18 23:07 srawlins

This could technically land in Mockito 3, as we haven't released it yet, but I think we're too busy at the moment to execute the cleanup that this would require 😄 .

srawlins avatar Jul 11 '18 23:07 srawlins

If it is a flag as long as we leave the default as not throwing we should be able to land in 3 right?

TedSander avatar Jul 12 '18 03:07 TedSander

Whoops this fell off my radar and Mockito 3 landed. I say we add the feature in 3.x, default to not-throwing, and flip the default Mockito 4 or greater.

srawlins avatar Nov 02 '18 03:11 srawlins

Just checked, since this would be a good change for NNBD, and about 1/3 of all internal tests fail when flipping the default.

srawlins avatar Jul 16 '19 12:07 srawlins

Hi,

Is there currently any way to globally opt-in to this behavior?

tjarvstrand avatar Dec 09 '21 09:12 tjarvstrand

This is the default when using @GenerateMocks to generate mocks; otherwise the default has not changed. I think we can definitely do this in 2022 though (possibly much code to touch inside Google which relies on the current default).

srawlins avatar Dec 09 '21 16:12 srawlins