0

I have the following xUnit test. How should I do in order to mock Func<ClientWebSocket> with new ClientWebSocket() using NSubstitute?

Btw, in addition ClientFactory doesn't want to 100% unit test coverage. enter image description here

public sealed class WebSocketOptions
{
    public Func<ClientWebSocket> ClientFactory { get; set; } = () => new ClientWebSocket();
    public int MaxMessageSize { get; set; } = 8192;
}

[Fact]
public void Build_ShouldReturnOptions_WhenAllParametersAreSet()
{
    // Arrange
    var factory = ClientFactory;

    var sut = new WebSocketOptionsBuilder();
    var expected = new
    {
        ClientFactory = factory,
        MaxMessageSize = maxMessageSize
    };

    // Act
    var actual = sut
        .WithClientFactory(factory)
        .WithMaxMessageSize(maxMessageSize)
        .Build();

    // Assert
    actual.Should().BeEquivalentTo(expected);

    ClientWebSocket ClientFactory()
    {
        return new ClientWebSocket();
    }
nop
  • 4,711
  • 6
  • 32
  • 93
  • 1
    Is there a problem with this code? The coverage of the function will inherently be 0 because it's never invoked, and that's exactly what you want to begin with. You don't need a mock for an object if you can provide an actual instance that does just as well, in the same way you don't mock `int`. Perhaps a slightly better test would be to implement `ClientFactory` along the lines of `clientFactoryIsTheSame = true; return default` and after testing actually call `actual.ClientFactory` to verify the boolean gets set, which as a bonus also handles the code coverage. – Jeroen Mostert Oct 26 '22 at 16:03
  • @JeroenMostert there is no problem in the code except the fact that I cannot test (). May you show an example of how to do that? – nop Oct 26 '22 at 18:29
  • 1
    You don't need to test `()` because it is not the code under test, it's a compiler-generated member to represent the lambda. If you *really* want code coverage for it, you would have to write a method that does `new WebSocketOptions().ClientFactory()`. No mocks, no testing, just straight up calling the member you get when the default constructor is invoked. If you really want to you can package that as some sort of test (`new WebSocketOptions().ClientFactory().Should().NotBeNull()`), though it's of questionable value. – Jeroen Mostert Oct 26 '22 at 18:35

0 Answers0