我有下面的控制器通过NServiceBus IEndpointInstance(全双工响应/请求解决方案)进行通信。我想测试放在这个控制器中的验证,所以我需要通过一个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>();
}
答案 0 :(得分:2)
我为IEndpointInstance https://docs.particular.net/samples/unit-testing/#testing-iendpointinstance-usage
添加了doco给定控制器
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);
}