Auto mocking services #500
egil
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
A fallback service provider added to bUnit's root service provider is invoked if the root service provider cannot resolve a
GetService
request. With that info in mind, we can use Moq (or another mocking framework in a similar fashion shown below) and a little reflection trickery to create a fallback service provider, which is really just something that implements theIServiceProvider
interface, that will use Moq to create a mocked version of a requested service, when itsGetService
method is called.AutoMockingServiceProvider
The auto moclking service provider will use Moq to create a mock of a requested service type once, and any subsequent requests will get the same type returned (they are saved in the mockedTypes dictionary).
The reason for saving the mocked services is that you can retrieve the same mocked instance of a type in both your test and in the component under test, which allows you to configure the mock in your test.
The
GetMockedService
extension method below makes it easy to pull out a Mock from the service provider.NOTE: This code doesn't deal with any edge cases, so it might not work in all cases, but should serve as a good starting point.
Example usage
Suppose we have the following component,
<MyComp>
:That depends on this interface:
This was tested with .NET 6 rc.1, Moq 4.16.1, and bunit 1.2.49.
Beta Was this translation helpful? Give feedback.
All reactions