commit | 044b193ef560b7bb1d94a1040771529c4438ed4a | [log] [tgz] |
---|---|---|
author | davidmorgan <davidmorgan@google.com> | Tue Aug 04 05:13:52 2020 -0400 |
committer | Sam Rawlins <sam.rawlins@gmail.com> | Mon Aug 24 14:01:58 2020 -0700 |
tree | b9f1afcfdc7c95385afff98edf54845f8cdced06 | |
parent | 4ac6b6edc2372eff75f78ddadc4f64fa6c59b684 [diff] |
Update //third_party/dart_lang/v2 and macos_sdk to 0a19e8dbfe53d2a9a8fd6850172dce89f96a42e9. Unbundle packages. Fix version used to turn on null safety in mockito tests. Update //third_party/dart_lang/trunk to 0a19e8dbfe53d2a9a8fd6850172dce89f96a42e9. - 0a19e8dbfe53d2a9a8fd6850172dce89f96a42e9 Add test requested in earlier CL by Brian Wilkerson <brianwilkerson@google.com> - d3945b56f737ccaf55c86ef0795fce931f44ee7e [ Service ] Fix issue where VM would hang in ServiceIsola... by Ben Konyi <bkonyi@google.com> - 7bb0d1f39ade6235cb73784a1e8443ad055edb12 [package:js] Add error for params in factories of anon cl... by Srujan Gaddam <srujzs@google.com> - 43c68d782df40b28873d9814ce2958ef30a3ff40 bulk fix for `prefer_adjacent_string_concatenation` by pq <pquitslund@google.com> - 3ec7ea15ecef3afcb1a569f00c452761c22ccad2 [vm] Fix some Fuchsia tests by Liam Appelbe <liama@google.com> - 6a66061703ee4d955b0720b58e8520f2b9368444 [ Service ] Add getWebSocketTarget RPC to allow for Obser... by Ben Konyi <bkonyi@google.com> - 536b466be39d0b2e2f4019f83a9f224e45ef11e3 Add tests for unused_element for mixins by Brian Wilkerson <brianwilkerson@google.com> - 7723fbb46da686ac392a0d718ffb262cc32b7398 Don't report DEAD_CODE hint for all required switch/case ... by Konstantin Shcheglov <scheglov@google.com> - 2bf777ea6e4329cd4f7b651731beee45e09d8db2 bulk fix for `omit_local_variable_types` by pq <pquitslund@google.com> - 987c9e347ca4e4fce5926b629b929f925a39dee8 bulk fix for `null_closures` by pq <pquitslund@google.com> - ac79402072ac2043a78b3bec44d39653fb894761 remove-duplicate-case should not remove statements if the... by Brian Wilkerson <brianwilkerson@google.com> - 40b880ee61a7896c0ba34f066607c4843df3843e [ddc] Fix import names in ddb script by Nicholas Shahan <nshahan@google.com> - d427ab510d93927fc6a772b6caa6d4e7e5df42dd bulk fix for `no_duplicate_case_values` by pq <pquitslund@google.com> - 6b9b934d84c2ef88248ff4cf5235371a30fda3c4 [vm, gc] Reduce growth rate as the heap size approaches -... by Ryan Macnak <rmacnak@google.com> - 0f0e04ec3afaa8265b8ec9e5d3e579c0a0c6c9d0 Add empty value class transformer. by jlcontreras <jlcontreras@google.com> - 25e08663cef1f2a7b755c37e642b2e141c93e5bb [cfe] Pass return type as part of callee type for invocat... by Johnni Winther <johnniwinther@google.com> - 56ba48670941b50934d6d6eeb22f276ffb1965c9 [co19] Roll co19 to e3d6ccfe8fa278041316f7dc958fdd8c2b447... by Alexander Thomas <athom@google.com> - ad9c73cb327098e1a31cfe7520ef037d5afe90c8 [cfe] Use promoted type as type context in variable assig... by Johnni Winther <johnniwinther@google.com> PiperOrigin-RevId: 324772678
Mock library for Dart inspired by Mockito.
import 'package:mockito/mockito.dart'; // Real class class Cat { String sound() => "Meow"; bool eatFood(String food, {bool hungry}) => true; Future<void> chew() async => print("Chewing..."); int walk(List<String> places) => 7; void sleep() {} void hunt(String place, String prey) {} int lives = 9; } // Mock class class MockCat extends Mock implements Cat {} // Create mock object. var cat = MockCat();
By declaring a class which extends Mockito's Mock class and implements the Cat class under test, we have a class which supports stubbing and verifying.
Using Dart's new null safety feature? Read the NULL_SAFETY_README for help on creating mocks of classes featuring non-nullable types.
// Interact with the mock object. cat.sound(); // Verify the interaction. verify(cat.sound());
Once created, the mock instance will remember all interactions. Then you can selectively verify
(or verifyInOrder
, or verifyNever
) the interactions you are interested in.
// Unstubbed methods return null. expect(cat.sound(), nullValue); // Stub a mock method before interacting. when(cat.sound()).thenReturn("Purr"); expect(cat.sound(), "Purr"); // You can call it again. expect(cat.sound(), "Purr"); // Let's change the stub. when(cat.sound()).thenReturn("Meow"); expect(cat.sound(), "Meow"); // You can stub getters. when(cat.lives).thenReturn(9); expect(cat.lives, 9); // You can stub a method to throw. when(cat.lives).thenThrow(RangeError('Boo')); expect(() => cat.lives, throwsRangeError); // We can calculate a response at call time. var responses = ["Purr", "Meow"]; when(cat.sound()).thenAnswer((_) => responses.removeAt(0)); expect(cat.sound(), "Purr"); expect(cat.sound(), "Meow");
By default, any instance method of the mock instance returns null
. The when
, thenReturn
, thenAnswer
, and thenThrow
APIs provide a stubbing mechanism to override this behavior. Once stubbed, the method will always return stubbed value regardless of how many times it is called. If a method invocation matches multiple stubs, the one which was declared last will be used.
Using thenReturn
to return a Future
or Stream
will throw an ArgumentError
. This is because it can lead to unexpected behaviors. For example:
Future
, unexpected behavior could occur.Future
or Stream
and it doesn't get consumed in the same run loop, it might get consumed by the global exception handler instead of an exception handler the consumer applies.Instead, use thenAnswer
to stub methods that return a Future
or Stream
.
// BAD when(mock.methodThatReturnsAFuture()) .thenReturn(Future.value('Stub')); when(mock.methodThatReturnsAStream()) .thenReturn(Stream.fromIterable(['Stub'])); // GOOD when(mock.methodThatReturnsAFuture()) .thenAnswer((_) async => 'Stub'); when(mock.methodThatReturnsAStream()) .thenAnswer((_) => Stream.fromIterable(['Stub']));
If, for some reason, you desire the behavior of thenReturn
, you can return a pre-defined instance.
// Use the above method unless you're sure you want to create the Future ahead // of time. final future = Future.value('Stub'); when(mock.methodThatReturnsAFuture()).thenAnswer((_) => future);
Mockito provides the concept of the “argument matcher” (using the class ArgMatcher) to capture arguments and to track how named arguments are passed. In most cases, both plain arguments and argument matchers can be passed into mock methods:
// You can use plain arguments themselves when(cat.eatFood("fish")).thenReturn(true); // ... including collections when(cat.walk(["roof","tree"])).thenReturn(2); // ... or matchers when(cat.eatFood(argThat(startsWith("dry")))).thenReturn(false); when(cat.eatFood(any)).thenReturn(false); // ... or mix aguments with matchers when(cat.eatFood(argThat(startsWith("dry")), hungry: true)).thenReturn(true); expect(cat.eatFood("fish"), isTrue); expect(cat.walk(["roof","tree"]), equals(2)); expect(cat.eatFood("dry food"), isFalse); expect(cat.eatFood("dry food", hungry: true), isTrue); // You can also verify using an argument matcher. verify(cat.eatFood("fish")); verify(cat.walk(["roof","tree"])); verify(cat.eatFood(argThat(contains("food")))); // You can verify setters. cat.lives = 9; verify(cat.lives=9);
If an argument other than an ArgMatcher (like any
, anyNamed
, argThat
, captureThat
, etc.) is passed to a mock method, then the equals
matcher is used for argument matching. If you need more strict matching consider use argThat(same(arg))
.
However, note that null
cannot be used as an argument adjacent to ArgMatcher arguments, nor as an un-wrapped value passed as a named argument. For example:
verify(cat.hunt("backyard", null)); // OK: no arg matchers. verify(cat.hunt(argThat(contains("yard")), null)); // BAD: adjacent null. verify(cat.hunt(argThat(contains("yard")), argThat(isNull))); // OK: wrapped in an arg matcher. verify(cat.eatFood("Milk", hungry: null)); // BAD: null as a named argument. verify(cat.eatFood("Milk", hungry: argThat(isNull))); // BAD: null as a named argument.
Mockito currently has an awkward nuisance to its syntax: named arguments and argument matchers require more specification than you might think: you must declare the name of the argument in the argument matcher. This is because we can‘t rely on the position of a named argument, and the language doesn’t provide a mechanism to answer “Is this element being used as a named element?”
// GOOD: argument matchers include their names. when(cat.eatFood(any, hungry: anyNamed('hungry'))).thenReturn(true); when(cat.eatFood(any, hungry: argThat(isNotNull, named: 'hungry'))).thenReturn(false); when(cat.eatFood(any, hungry: captureAnyNamed('hungry'))).thenReturn(false); when(cat.eatFood(any, hungry: captureThat(isNotNull, named: 'hungry'))).thenReturn(true); // BAD: argument matchers do not include their names. when(cat.eatFood(any, hungry: any)).thenReturn(true); when(cat.eatFood(any, hungry: argThat(isNotNull))).thenReturn(false); when(cat.eatFood(any, hungry: captureAny)).thenReturn(false); when(cat.eatFood(any, hungry: captureThat(isNotNull))).thenReturn(true);
Use verify
or verifyNever
:
cat.sound(); cat.sound(); // Exact number of invocations verify(cat.sound()).called(2); // Or using matcher verify(cat.sound()).called(greaterThan(1)); // Or never called verifyNever(cat.eatFood(any));
Use verifyInOrder
:
cat.eatFood("Milk"); cat.sound(); cat.eatFood("Fish"); verifyInOrder([ cat.eatFood("Milk"), cat.sound(), cat.eatFood("Fish") ]);
Verification in order is flexible - you don't have to verify all interactions one-by-one but only those that you are interested in testing in order.
verifyZeroInteractions(cat);
cat.sound(); verify(cat.sound()); verifyNoMoreInteractions(cat);
Use the captureAny
, captureThat
, and [captureNamed
] argument matchers:
// Simple capture cat.eatFood("Fish"); expect(verify(cat.eatFood(captureAny)).captured.single, ["Fish"]); // Capture multiple calls cat.eatFood("Milk"); cat.eatFood("Fish"); expect(verify(cat.eatFood(captureAny)).captured, ["Milk", "Fish"]); // Conditional capture cat.eatFood("Milk"); cat.eatFood("Fish"); expect(verify(cat.eatFood(captureThat(startsWith("F")))).captured, ["Fish"]);
Use untilCalled
:
// Waiting for a call. cat.eatFood("Fish"); await untilCalled(cat.chew()); // Completes when cat.chew() is called. // Waiting for a call that has already happened. cat.eatFood("Fish"); await untilCalled(cat.eatFood(any)); // Completes immediately.
You can also write a simple fake class that implements a real class, by extending Fake. Fake allows your subclass to satisfy the implementation of your real class, without overriding the methods that aren't used in your test; the Fake class implements the default behavior of throwing UnimplementedError (which you can override in your fake class):
// Fake class class FakeCat extends Fake implements Cat { @override bool eatFood(String food, {bool hungry}) { print('Fake eat $food'); return true; } } void main() { // Create a new fake Cat at runtime. var cat = FakeCat(); cat.eatFood("Milk"); // Prints 'Fake eat Milk'. cat.sleep(); // Throws. }
Use reset
:
// Clearing collected interactions: cat.eatFood("Fish"); clearInteractions(cat); cat.eatFood("Fish"); verify(cat.eatFood("Fish")).called(1); // Resetting stubs and collected interactions: when(cat.eatFood("Fish")).thenReturn(true); cat.eatFood("Fish"); reset(cat); when(cat.eatFood(any)).thenReturn(false); expect(cat.eatFood("Fish"), false);
Use [logInvocations
] and throwOnMissingStub
:
// Print all collected invocations of any mock methods of a list of mock objects: logInvocations([catOne, catTwo]); // Throw every time that a mock method is called without a stub being matched: throwOnMissingStub(cat);
Testing with real objects is preferred over testing with mocks - if you can construct a real instance for your tests, you should! If there are no calls to verify
in your test, it is a strong signal that you may not need mocks at all, though it‘s also OK to use a Mock
like a stub. When it’s not possible to use the real object, a tested implementation of a fake is the next best thing - it's more likely to behave similarly to the real class than responses stubbed out in tests. Finally an object which extends Fake
using manually overridden methods is preferred over an object which extends Mock
used as either a stub or a mock.
A class which extends Mock
should never stub out it‘s own responses with when
in it’s constructor or anywhere else. Stubbed responses should be defined in the tests where they are used. For responses controlled outside of the test use @override
methods for either the entire interface, or with extends Fake
to skip some parts of the interface.
Similarly, a class which extends Mock
should never have any @override
methods. These can‘t be stubbed by tests and can’t be tracked and verified by Mockito. A mix of test defined stubbed responses and mock defined overrides will lead to confusion. It is OK to define static utilities on a class which extends Mock
if it helps with code structure.
Read more information about this package in the FAQ.