Skip to content

Commit 095add3

Browse files
authored
docs: Add Loose Automocker description (#1485)
* docs: Add Loose Automocker description Fixes #1478 * docs: Use correct nullability * docs: Add nullability
1 parent 0278363 commit 095add3

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

docs/site/docs/providing-input/inject-services-into-components.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,41 @@ Here is a test where the custom service provider is used via delegate:
8080

8181
[!code-csharp[](../../../samples/tests/xunit/CustomServiceProviderFactoryUsage.cs?start=25&end=29)]
8282

83+
## Using libraries like AutoMocker as fallback provider
84+
It is possible to use libraries that automatically create mock services as fallback service providers. Here is an example implementation that utilizes the AutoMocker
85+
86+
```csharp
87+
public class MockServiceProvider : IServiceProvider
88+
{
89+
private readonly AutoMocker _autoMocker = new AutoMocker();
90+
91+
public object? GetService(Type serviceType)
92+
{
93+
return _autoMocker.Get(serviceType);
94+
}
95+
}
96+
```
97+
98+
> [!WARNING]
99+
> An exception has to be made for `IComponentActivator`, if "Loose" mode is used. Otherwise, runtime exception can be thrown.
100+
101+
```csharp
102+
public class MockServiceProvider : IServiceProvider
103+
{
104+
private readonly AutoMocker _autoMocker = new AutoMocker(MockBehavior.Loose);
105+
106+
public object? GetService(Type serviceType)
107+
{
108+
if (serviceType == typeof(IComponentActivator))
109+
{
110+
return null;
111+
}
112+
113+
return _autoMocker.Get(serviceType);
114+
}
115+
}
116+
```
117+
83118
## Further reading
84119

85120
A closely related topic is mocking. To learn more about mocking in bUnit, go to the <xref:test-doubles> page.

0 commit comments

Comments
 (0)