|
1 | | -# Tips for developing with the generator |
| 1 | +# bUnit Generators |
| 2 | + |
| 3 | +This package contains source generators for bUnit, to make it easier and more convenient to write tests. |
| 4 | + |
| 5 | +## `AddGeneratedStub` Generator |
| 6 | +This generator adds the ability to automatically generate stubs for a given type. This comes in handy, when dealing |
| 7 | +with 3rd party components that might need an extensive setup. Here a small example: |
| 8 | + |
| 9 | +Given the following component |
| 10 | +```razor |
| 11 | +<ThirdPartyText Text="@count" /> |
| 12 | +<button @onclick="IncrementCount">Increase by one</button> |
| 13 | +@code { |
| 14 | + private int count; |
| 15 | + |
| 16 | + private void IncrementCount() |
| 17 | + { |
| 18 | + count++; |
| 19 | + } |
| 20 | +} |
| 21 | +``` |
| 22 | + |
| 23 | +If `ThirdPartyText` is a 3rd party component, that needs a lot of setup, it might be easier to just stub it out: |
| 24 | + |
| 25 | +```csharp |
| 26 | +[Fact] |
| 27 | +public void Text_button_gets_initial_count() |
| 28 | +{ |
| 29 | + // This call will automatically generate a stub for the ThirdPartyButton component |
| 30 | + // with the name "ThirdPartyButtonStub" |
| 31 | + ComponentFactories.AddGeneratedStub<ThirdPartyText>(); |
| 32 | + var cut = Render<Counter>(@<Counter />); |
| 33 | + |
| 34 | + cut.Find("button").Click(); |
| 35 | + |
| 36 | + // Retrieves the stub from the render tree and checks if the text is "1" |
| 37 | + cut.FindComponent<ThirdPartyTextStub>().Instance.Text.Should().Be("1"); |
| 38 | +} |
| 39 | +``` |
| 40 | + |
| 41 | +### Setup |
| 42 | +To use the generator, the **Interceptor** feature has to be used inside the csproj file: |
| 43 | + |
| 44 | +```xml |
| 45 | +<Project Sdk="Microsoft.NET.Sdk"> |
| 46 | + <PropertyGroup> |
| 47 | + <TargetFramework>net8.0</TargetFramework> |
| 48 | + <!-- This line is required to enable the generator and interceptor --> |
| 49 | + <InterceptorsPreviewNamespaces>$(InterceptorsPreviewNamespaces);Bunit</InterceptorsPreviewNamespaces> |
| 50 | +``` |
| 51 | + |
| 52 | +## Developer notes |
| 53 | + |
| 54 | +### Tips for developing with the generator |
2 | 55 |
|
3 | 56 | When changing the source generator, to see the effect, clearing the build cache may be necessary: |
4 | 57 |
|
|
0 commit comments