mockito
v5.6.4A mock framework inspired by Mockito with APIs for Fakes, Mocks, behavior verification, and stubbing.
Архив пакета: https://pubdev.letsnova.ru/api/archives/mockito/5.6.4.tar.gz
dart pub add mockitoREADME
Mock library for Dart inspired by Mockito.
Let's create mocks
Mockito 5.0.0 supports Dart's new null safety language feature in Dart 2.12, primarily with code generation.
To use Mockito's generated mock classes, add a build_runner dependency in your
package's pubspec.yaml file, under dev_dependencies; something like
build_runner: ^1.11.0.
For alternatives to the code generation API, see the NULL_SAFETY_README.
Let's start with a Dart library, cat.dart:
import 'package:mockito/annotations.dart';
import 'package:mockito/mockito.dart';
// Annotation which generates the cat.mocks.dart library and the MockCat class.
@GenerateNiceMocks([MockSpec<Cat>()])
import 'cat.mocks.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;
}
void main() {
// Create mock object.
var cat = MockCat();
}
By annotating the import of a .mocks.dart library with @GenerateNiceMocks,
you are directing Mockito's code generation to write a mock class for each
"real" class listed, in a new library.
The next step is to run build_runner in order to generate this new library:
dart run build_runner build
# OR
dart run build_runner build
build_runner will generate a file with a name based on the file containing the
@GenerateNiceMocks annotation. In the above cat.dart example, we import the
generated library as cat.mocks.dart.
NOTE: by default only annotations in files under test/ are processed, if
you want to add Mockito annotations in other places, you will need to add a
build.yaml file to your project, see this SO answer.
The generated mock class, MockCat, extends Mockito's Mock class and implements
the Cat class, giving us a class which supports stubbing and verifying.
Let's verify some behavior!
// 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.
How about some stubbing?
// 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");
// We can stub a method with multiple calls that happened in a particular order.
when(cat.sound()).thenReturnInOrder(["Purr", "Meow"]);
expect(cat.sound(), "Purr");
expect(cat.sound(), "Meow");
expect(() => cat.sound(), throwsA(isA<StateError>()));
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. It is worth noting that stubbing and verifying only works on methods of
a mocked class; in this case, an instance of MockCat must be used, not an
instance of Cat.
A quick word on async stubbing
Using thenReturn to return a Future or Stream will throw an
ArgumentError. This is because it can lead to unexpected behaviors. For
example:
- If the method is stubbed in a different zone than the zone that consumes the
Future, unexpected behavior could occur. - If the method is stubbed to return a failed
FutureorStreamand 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);
Argument matchers
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 `any`
when(cat.eatFood(any)).thenReturn(false);
// ... or 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);
// ... or mix arguments 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 using argThat(identical(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.
Named arguments
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);
Verifying exact number of invocations / at least x / never
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));
Verification in order
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.
Making sure interaction(s) never happened on mock
verifyZeroInteractions(cat);
Finding redundant invocations
cat.sound();
verify(cat.sound());
verifyNoMoreInteractions(cat);
Capturing arguments for further assertions
Use the captureAny, captureThat, and captureAnyNamed 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"]);
Waiting for an interaction
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.
Nice mocks vs classic mocks
Mockito provides two APIs for generating mocks, the @GenerateNiceMocks
annotation and the @GenerateMocks annotation. The recommended API is
@GenerateNiceMocks. The difference between these two APIs is in the behavior
of a generated mock class when a method is called and no stub could be found.
For example:
void main() {
var cat = MockCat();
cat.sound();
}
The Cat.sound method returns a non-nullable String, but no stub has been made
with when(cat.sound()), so what should the code do? What is the "missing stub"
behavior?
- The "missing stub" behavior of a mock class generated with
@GenerateMocksis to throw an exception. - The "missing stub" behavior of a mock class generated with
@GenerateNiceMocksis to return a "simple" legal value (for example, a non-nullvalue for a non-nullable return type). The value should not be used in any way; it is returned solely to avoid a runtime type exception.
Mocking a Function type
To create mocks for Function objects, write an abstract class with a method
for each function type signature that needs to be mocked. The methods can be
torn off and individually stubbed and verified.
@GenerateMocks([Cat, Callbacks])
import 'cat_test.mocks.dart'
abstract class Callbacks {
Cat findCat(String name);
}
void main() {
var mockCat = MockCat();
var findCatCallback = MockCallbacks().findCat;
when(findCatCallback('Pete')).thenReturn(mockCat);
}
Writing a fake
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.
}
Resetting mocks
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);
Debugging
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);
Best Practices
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. Data models never need to
be mocked if they can be constructed with stubbed data. 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 its own responses with
when in its 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 implementation.
It should not define any @override methods, and it should not mixin any
implementations. Actual member definitions 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.
Frequently asked questions
Read more information about this package in the FAQ.
История изменений
5.6.4
- Allow
analyzer11.0.0 and 12.0.0. - Move to
dart-lang/buildmonorepo.
5.6.3
- Allow
analyzer: >=8.1.0 <11.0.0.
5.6.2
- Avoid exceptions from equality operators when comparing query arguments to
SmartFakeactual arguments.
5.6.1
- Allow
analyzer: >=8.1.0 <10.0.0.
5.6.0
- Add dummy values for
RegExpandMapEntry.
5.5.1
- Require
analyzer: ^8.1.0. - Allow
source_gen: '>=3.0.0 <5.0.0'. - Allow
build: '>=3.0.0 <5.0.0'.
5.5.0
- Switch to
build3.0.0. - Require Dart SDK ^3.7.0.
5.5.0-dev
- Switch to
build3.0.0-dev. - Require Dart SDK ^3.7.0.
5.4.6
- When formatting a generated mocks library, use the language version of the library with the mockito annotation.
5.4.5
- Ignore "must_be_immutable" warning in generated files. Mocks cannot be made immutable anyway, but this way users aren't prevented from using generated mocks altogether.
- Require Dart SDK ^3.6.0.
- Require
analyzer: '>=6.9.0 <8.0.0'. - Require
dart_style: '>=2.3.7 <4.0.0', so that the current Dart language version can be passed toDartFormatter. - Require
source_gen: ">=1.4.0 <3.0.0". - Add support for extension types.
- Add topics to
pubspec.yaml. - Fix a bug where type aliases in type arguments were not correctly resolved.
- Fix a bug where record types were not correctly resolved.
5.4.4
- Use
posixstyle for local imports. - Allow test_api ^0.7.0.
5.4.3
- Require analyzer 5.12.0, allow analyzer version 6.x;
- Add example of writing a class to mock function objects.
- Add support for the
build_extensionsbuild.yaml option - Require Dart >=3.1.0.
- Potentially breaking Changed default
Stringvalue returned by nice mocks' unstubbed method to include some useful info. This could break the tests that relied on getting an emptyStringfrom unstubbed methods. - Remove deprecated
returnNullOnMissingStubandOnMissingStub.returnNullMockSpecoptions.
5.4.2
- Require code_builder 4.5.0.
- Add support for records.
- Fixed the bug with missing imports for unused type alias arguments.
5.4.1
- Deprecate the
mixingInargument toMockSpec. Best practice is to avoid any concrete implementation in classes which extendMock. - Fixed generation for clashing type variable names.
- Require Dart >= 2.19.0.
- Require analyzer 5.11.0.
- Fail to generate mocks of
sealed/base/finalclasses. - Add new
thenReturnInOrdermethod to mock multiple calls to a single method in order. - Add
provideDummy/provideDummyBuilderfunctions for users to supply dummy values to Mockito, to cover cases where codegen can't create one. - Allow generating mocks for classes with methods/getters returning non-nullable unknown types.
5.4.0
- Fix nice mocks generation in mixed mode (generated code is pre null-safety, while mocked class is null-safe).
- Support typedef-aliased classes in
@GenerateMocksand@GenerateNiceMocks - Breaking Default
generate_fortotest/**. Projects that are generating mocks for libraries outside of thetest/directory should add an explicitgenerate_forargument to include files with mock generating annotations. - Require Dart >= 2.17.0.
- Require analyzer 5.2.0.
5.3.2
- Support analyzer 5.0.0.
5.3.1
- Fix analyzer and code_builder dependencies.
- Reference
@GenerateNiceMocksin documentation. - Allow generating a mock class which includes overriding members with private
types in their signature. Such members cannot be stubbed with mockito, and
will only be generated when specified in MockSpec
unsupportedMembers. - Include
requiredkeyword in functions used as default return values.
5.3.0
- Introduce a new
MockSpecparameter,onMissingStub, which allows specifying three actions to take when a real call is made to a mock method with no matching stub. The two existing behaviors are the default behavior of throwing an exception, and the legacy behavior of returningnull. A new behavior is also introduced: returning a legal default value. With this behavior, legal default values are returned for any given type. - Deprecate the
MockSpecreturnNullOnMissingStubparameter in favor of the newonMissingStubparameter. - Introduce a new
@GenerateNiceMocksannotation, that uses the new "return a legal value" behavior for missing stubs. - Add
SmartFakeclass to be used as a return values for unstubbed methods. It remembers where it was created and throws a descriptive error in case the fake is later used. - Include
requiredkeyword in function types to match overridden function types.
5.2.0
- Fix generation of methods with return type of
FutureOr<T>for generic, potentially nullableT. - Support
@GenerateMocksannotations onimportandexportdirectives. - Support analyzer 4.x.
5.1.0
- In creating mocks for a pre-null-safe library, opt out of null safety in the generated code.
- Properly generate method overrides for methods with covariant parameters. #506
- Correctly generate a
toStringoverride method for pre-null safe libraries, for which the class-to-mock implementstoStringwith additional parameters. - Improve messaging in a MissingStubError, directing to the docs for MockSpec.
- Fix incorrect error when trying to mock a method with a parameter with inner function types (like in type arguments) which are potentially non-nullable. #476
- Allow fallback generators to be applied for getters.
- Support generating a mock class for a class with members with non-nullable
unknown return types via a new parameter on
MockSpeccalledunsupportedMembers. See NULL_SAFETY_README for details.
5.0.17
- Report when a class cannot be mocked because an inherited method or property accessor requires a private type. #446
- Do not needlessly implement
toStringunless the class-to-mock implementstoStringwith additional parameters. #461 - Support analyzer 3.x.
5.0.16
- Fix type reference for nested, imported types found in type arguments on a custom class-to-mock. #469
- Bump minimum analyzer dependency to version 2.1.0.
- Ignore
camel_case_typeslint in generated code.
5.0.15
- Fix an issue generating the correct parameter default value given a constructor which redirects to a constructor declared in a separate library. #459
5.0.14
- Generate Fake classes with unique names. #441
5.0.13
- Implement methods which have been overridden in the mixin hierarchy properly. Previously, mixins were being applied in the wrong order, which could skip over one method that overrides another with a different signature. #456
5.0.12
- Use an empty list with a correct type argument for a fallback value for a method which returns Iterable. #445
- When selecting the library that should be imported in order to reference a type, prefer a library which exports the library in which the type is declared. This avoids some confusion with conditional exports. #443
- Properly reference types in overridden
toStringimplementations. #438 - Override
toStringin a Fake implementation when the class-to-be-faked has a superclass which overridestoStringwith additional parameters. #371 - Support analyzer 2.x.
5.0.11
- Allow two mocks of the same class (with different type arguments) to be specified with different fallback generators.
- Allow fallback generators on super types of a mocked class.
- Avoid
inference_failure_on_instance_creationerrors in generated code. - Ignore
implementation_importslint in generated code. - Support methods with
FunctionandFuture<Function>return types.
5.0.10
- Generate a proper mock class when the mocked class overrides
toString,hashCode, oroperator==. #420 - Override
toStringimplementation on generated Fakes in order to match the signature of an overriding method which adds optional parameters. #371 Properly type methods in a generated mock class which comes from a "custom mock" annotation referencing an implicit type. Given a method which references type variables defined on their enclosing class (for example,Tinclass Foo<T>), mockito will now correctly referenceTin generated code. #422
5.0.9
- Mock classes now implement a type's nested type arguments properly. #410
- Mock classes now implement API from a class's interface(s) (in addition to superclasses and mix ins). Thanks @markgravity. #404
- A MockSpec passed into a
@GenerateMocksannotation'scustomMockslist can now specify "fallback generators." These are functions which can be used to generate fake responses that mockito's code generation needs in order to return a value for a method with a generic return type. See NULL_SAFETY_README for details.
5.0.8
- Migrate Mockito codegen to null safety.
- Support mocking methods with typed_data List return types.
- Support mocking methods with return types declared in private SDK libraries
(such as HttpClient and WebSocket, declared in
dart:_http). - Do not generate a fake for a class which is only used as a nullable type in a Future. #409
5.0.7
- Properly refer to type parameter bounds with import prefixes. #389
- Stop referring to private typedefs in generated code. #396
- Ignore
prefer_const_constructorsandavoid_redundant_argument_valueslint rule violations in generated code.
5.0.6
- Support the 0.4.x releases of
test_api.
5.0.5
- Support 4.x releases of code_builder.
5.0.4
- Allow calling methods with void return types w/o stubbing. #367
- Add type argument to dummy
Futurereturn value. #380
5.0.3
- Support 1.x releases of source_gen.
5.0.2
- Support the latest build packages and dart_style.
5.0.1
- Update to the latest test_api.
- Fix mock generation of type which has a supertype which mixes in a mixin.
- Fix mock generation of method which returns a non-nullable generic function type.
5.0.0
verifyInOrdernow returns aList<VerificationResult>which stores arguments which were captured in a call toverifiyInOrder.- Breaking change: Remove the public constructor for
VerificationResult. - Doesn't allow
verifybeen used inside theverifyInOrder.
5.0.0-nullsafety.7
- Fix generation of duplicate mock getters and setters from inherited classes.
5.0.0-nullsafety.6
- Fix generation of method with a parameter with a default value which includes a top-level function.
- Migrate example code to null safety.
- Breaking change: Change the error which is thrown if a method is called and no method stub was found, from NoSuchMethodError to MissingStubError.
- Breaking change:
Mock.noSuchMethod's optional positional parameter, "returnValue" is changed to a named parameter, and a second named parameter is added. Any manual mocks which callMock.noSuchMethodwith a second positional argument will need to instead use the named parameter. - Allow real calls to mock methods which return
void(like setters) orFuture<void>, even if unstubbed.
5.0.0-nullsafety.5
- Fix
noSuchMethodinvocation of setters in generated mocks.
5.0.0-nullsafety.4
- Annotate overridden getters and setters with
@override.
5.0.0-nullsafety.3
- Improve static analysis of generated code.
- Make implicit casts from dynamic in getters explicit.
5.0.0-nullsafety.2
- Fix issue with generated code which references a class declared in a part (#310).
5.0.0-nullsafety.1
- Fix an issue with generated mocks overriding methods from Object, such as
operator ==(#306). - Fix an issue with relative imports in generated mocks.
5.0.0-nullsafety.0
- Migrate the core libraries and tests to null safety. The builder at
lib/src/builder.dartopts out of null safety. - Add
httpback todev_dependencies. It's used by the example. - Remove deprecated
typed,typedArgThat, andtypedCaptureThatAPIs.
4.1.3
- Allow using analyzer 0.40.
throwOnMissingStubaccepts an optional argument,exceptionBuilder, which will be called to build and throw a custom exception when a missing stub is called.
4.1.2
- Introduce experimental code-generated mocks. This is primarily to support the new "Non-nullable by default" (NNBD) type system coming soon to Dart.
- Add an optional second parameter to
Mock.noSuchMethod. This may break clients who use the Mock class in unconventional ways, such as overridingnoSuchMethodon a class which extends Mock. To fix, or prepare such code, add a second parameter to such overridingnoSuchMethoddeclaration. - Increase minimum Dart SDK to
2.7.0. - Remove Fake class; export identical Fake class from the test_api package.
4.1.1
- Mark the unexported and accidentally public
setDefaultResponseas deprecated. - Mark the not useful, and not generally used,
namedfunction as deprecated. - Produce a meaningful error message if an argument matcher is used outside of
stubbing (
when) or verification (verifyanduntilCalled).
4.1.0
- Add a
Fakeclass for implementing a subset of a class API as overrides without misusing theMockclass.
4.0.0
-
Replace the dependency on the test package with a dependency on the new test_api package. This dramatically reduces mockito's transitive dependencies.
This bump can result in runtime errors when coupled with a version of the test package older than 1.4.0.
3.0.2
- Rollback the test_api part of the 3.0.1 release. This was breaking tests that use Flutter's current test tools, and will instead be released as part of Mockito 4.0.0.
3.0.1
- Replace the dependency on the test package with a dependency on the new test_api package. This dramatically reduces mockito's transitive dependencies.
- Internal improvements to tests and examples.
3.0.0
-
Deprecate the
typedAPI; instead of wrapping other Mockito API calls, likeany,argThat,captureAny, andcaptureArgThat, with a call totyped, the regular API calls are to be used by themselves. PassinganyandcaptureAnyas named arguments must be replaced withanyNamed()andcaptureAnyNamed, respectively. PassingargThatandcaptureThatas named arguments must include thenamedparameter. -
Introduce a backward-and-forward compatible API to help users migrate to Mockito 3. See more details in the upgrading-to-mockito-3 doc.
-
thenReturnnow throws anArgumentErrorif either aFutureorStreamis provided.thenReturncalls with futures and streams should be changed tothenAnswer. See the README for more information. -
Support stubbing of void methods in Dart 2.
-
thenReturnandthenAnswernow support generics and infer the correct types from thewhencall. -
Completely remove the mirrors implementation of Mockito (
mirrors.dart). -
Fix compatibility with new noSuchMethod Forwarding feature of Dart 2. This is thankfully a mostly backwards-compatible change. This means that this version of Mockito should continue to work:
- with Dart
>=2.0.0-dev.16.0, - with Dart 2 runtime semantics (i.e. with
dart --preview-dart-2, or with Flutter Beta 3), and - with the new noSuchMethod Forwarding feature, when it lands in CFE, and when it lands in DDC.
This change, when combined with noSuchMethod Forwarding, will break a few code paths which do not seem to be frequently used. Two examples:
class A { int fn(int a, [int b]) => 7; } class MockA extends Mock implements A {} var a = new MockA(); when(a.fn(typed(any), typed(any))).thenReturn(0); print(a.fn(1));This used to print
null, because only one argument was passed, which did not match the two-argument stub. Now it will print0, as the real call contains a value for both the required argument, and the optional argument.a.fn(1); a.fn(2, 3); print(verify(a.fn(typed(captureAny), typed(captureAny))).captured);This used to print
[2, 3], because only the second call matched theverifycall. Now, it will print[1, null, 2, 3], as both real calls contain a value for both the required argument, and the optional argument. - with Dart
-
Upgrade package dependencies.
-
Throw an exception when attempting to stub a method on a Mock object that already exists.
2.2.0
- Add new feature to wait for an interaction:
untilCalled. See the README for documentation. capture*calls outside of averify*call no longer capture arguments.- Some collections require stricter argument matching. For example, a stub like:
mock.methodWithListArgs([1,2,3].map((e) => e*2))(note theIterableargument) will no longer match the following stub:when(mock.methodWithListArgs([42])).thenReturn(7);.
2.1.0
- Add documentation for
when,verify,verifyNever,resetMockitoState. - Expose
throwOnMissingStub,resetMockitoState. - Improve failure message for
verify. - SDK version ceiling bumped to
<2.0.0-dev.infinityto support Dart 2.0 development testing. - Add a Mockito + test package example at
test/example/iss.
2.0.2
- Start using the new
InvocationMatcherinstead of the old matcher. - Change
throwOnMissingStubback to invokingObject.noSuchMethod:- It was never documented what the thrown type should be expected as.
- You can now just rely on
throwsNoSuchMethodErrorif you want to catch it.
2.0.1
- Add a new
throwOnMissingStubmethod to the API.
2.0.0
- Removed
mockito_no_mirrors.dart
2.0.0-dev
- Remove export of
spyand anydart:mirrorsbased API frommockito.dart. Users may import aspackage:mockito/mirrors.dartgoing forward. - Deprecated
mockito_no_mirrors.dart; replace withmockito.dart. - Require Dart SDK
>=1.21.0 <2.0.0to use generic methods.
1.0.1
- Add a new
thenThrowmethod to the API. - Document
thenAnswerin the README. - Add more dartdoc.
1.0.0
- Add a new
typedAPI that is compatible with Dart Dev Compiler; documented in README.md.
0.11.1
- Move the reflection-based
spycode into a private source file. Nowpackage:mockito/mockito.dartincludes this reflection-based API, and a newpackage:mockito/mockito_no_mirrors.dartdoesn't require mirrors.
0.11.0
- Equality matcher used by default to simplify matching collections as arguments. Should be non-breaking change in most cases, otherwise consider using
argThat(identical(arg)).
0.10.0
- Added support for spy.
0.9.0
- Migrate from the unittest package to use the new test package.
- Format code using dartformat
