|
| 1 | +#if NET5_0_OR_GREATER |
| 2 | + |
| 3 | +using Bunit.TestDoubles; |
| 4 | + |
| 5 | +namespace Bunit.Rendering; |
| 6 | + |
| 7 | +public class BunitComponentActivatorTest : TestContext |
| 8 | +{ |
| 9 | + [Fact(DisplayName = "Default activator")] |
| 10 | + public void Test001() |
| 11 | + { |
| 12 | + var activator = new CustomComponentActivator(); |
| 13 | + Services.AddSingleton<IComponentActivator>(activator); |
| 14 | + |
| 15 | + var cut = RenderComponent<Simple1>(); |
| 16 | + |
| 17 | + cut.Instance.ShouldBeOfType<Simple1>(); |
| 18 | + } |
| 19 | + |
| 20 | + [Fact(DisplayName = "Custom singleton IComponentActivator registered in Services")] |
| 21 | + public void Test002() |
| 22 | + { |
| 23 | + var activator = new CustomComponentActivator(); |
| 24 | + Services.AddSingleton<IComponentActivator>(activator); |
| 25 | + |
| 26 | + RenderComponent<Simple1>(); |
| 27 | + |
| 28 | + activator.RequestedComponentTypes |
| 29 | + .ShouldHaveSingleItem() |
| 30 | + .ShouldBe(typeof(Simple1)); |
| 31 | + } |
| 32 | + |
| 33 | + [Fact(DisplayName = "Custom singleton IComponentActivator registered in Services with ComponentFactories in use")] |
| 34 | + public void Test003() |
| 35 | + { |
| 36 | + var activator = new CustomComponentActivator(); |
| 37 | + Services.AddSingleton<IComponentActivator>(activator); |
| 38 | + ComponentFactories.AddStub<ClickCounter>(); |
| 39 | + |
| 40 | + var cut = RenderComponent<Wrapper>(ps => ps.AddChildContent<ClickCounter>()); |
| 41 | + |
| 42 | + activator.RequestedComponentTypes |
| 43 | + .ShouldHaveSingleItem() |
| 44 | + .ShouldBe(typeof(Wrapper)); |
| 45 | + cut.HasComponent<ClickCounter>().ShouldBeFalse(); |
| 46 | + cut.HasComponent<Stub<ClickCounter>>().ShouldBeTrue(); |
| 47 | + } |
| 48 | + |
| 49 | + private sealed class CustomComponentActivator : IComponentActivator |
| 50 | + { |
| 51 | + public List<Type> RequestedComponentTypes { get; } = new(); |
| 52 | + |
| 53 | + public IComponent CreateInstance(Type componentType) |
| 54 | + { |
| 55 | + RequestedComponentTypes.Add(componentType); |
| 56 | + return (IComponent)Activator.CreateInstance(componentType)!; |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +#endif |
0 commit comments