2017-09-14 47 views
0

我有下面的控制器通过NServiceBus IEndpointInstance(全双工响应/请求解决方案)进行通信。我想测试放置在这个控制器中的验证,所以我需要通过一个IEndpointInstance对象。不幸的是,在我能找到的特定网站的文档中没有提到这一点。如何模拟NServiceBus的IEndpointInstance

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

我有下面的测试代码,它编译,但它只是当我运行它挂起。我认为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>(); 
} 
+2

测试为什么不使用模拟框架,像起订量或FakeItEasy以便创建一个模拟IEndpointInstance – Alex

+1

提供的例子是不完整的。提供可用于表示问题的[mcve]。你还需要清楚你想要达到的目标。这是为了进行单元测试还是集成测试? – Nkosi

+0

@亚历克斯:好问题。我没有想到。让我试试看。 – SayusiAndo

回答

1

我加为DOCO IEndpointInstance 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); 
} 
+0

谢谢,我的生活现在好多了! :)但是,只是通过一个Moq对象实现IEndpointInstance的工作也很好。 – SayusiAndo