如何模拟 NServiceBus 的 IEndpointInstance

How to mock out IEndpointInstance of NServiceBus

我有下面的控制器,它通过 NServiceBus IEndpointInstance(全双工 response/request 解决方案)进行通信。我想测试放置在这个控制器中的验证,所以我需要传递一个 IEndpointInstance 对象。不幸的是,在我能找到的 Particular 站点的文档中没有提到这一点。

NServiceBus.Testing nuget 包中我找到了 TestableEndpointInstance class,但我不知道如何使用它。

我有下面的测试代码,它可以编译,但是当我 运行 它时它就挂了。我认为 TestableEndpointInstance 参数化有问题。

有人能帮我举个例子吗?

控制器:

public CountryController(
    IEndpointInstance endpointInstance,
    IMasterDataContractsValidator masterDataContractsValidator)
{
    this.endpointInstance = endpointInstance;
    this._masterDataContractsValidator = masterDataContractsValidator;
}

[HttpPost]
[Route("Add")]
public async Task<HttpResponseMessage> Add([FromBody] CountryContract countryContract)
{
    try
    {
        CountryRequest countryRequest = new CountryRequest();
        this._masterDataContractsValidator.CountryContractValidator.ValidateWithoutIdAndThrow(countryContract);

        countryRequest.Operation = CountryOperations.Add;
        countryRequest.CountryContracts.Add(countryContract);

        // nservicebus communication towards endpoint

        return message;
    }
    catch (Exception e)
    {
        var message = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, e.Message);
        return message;
    }
}

测试:

public CountryControllerTests()
{
    TestableEndpointInstance endpointInstance = new TestableEndpointInstance();
    // Validator instantiation
    this.countryController = new CountryController(endpointInstance, masterDataContractsValidator);
}


[Theory]
[MemberData("CountryControllerTestsAddValidation")]
public async void CountryControllerTests_Add_Validation(
    int testId,
    CountryContract countryContract)
{
    // Given

    // When
    Func<Task> action = async () => await this.countryController.Add(countryContract);

    // Then
    action.ShouldThrow<Exception>();
}

我为 IEndpointInstance 添加了 doco https://docs.particular.net/samples/unit-testing/#testing-iendpointinstance-usage

给定一个控制器

public class MyController
{
    IEndpointInstance endpointInstance;

    public MyController(IEndpointInstance endpointInstance)
    {
        this.endpointInstance = endpointInstance;
    }

    public Task HandleRequest()
    {
        return endpointInstance.Send(new MyMessage());
    }
}

可以用

测试
[Test]
public async Task ShouldSendMessage()
{
    var endpointInstance = new TestableEndpointInstance();
    var handler = new MyController(endpointInstance);

    await handler.HandleRequest()
        .ConfigureAwait(false);

    var sentMessages = endpointInstance.SentMessages;
    Assert.AreEqual(1, sentMessages.Length);
    Assert.IsInstanceOf<MyMessage>(sentMessages[0].Message);
}