У меня есть два модульных теста с почти одинаковой подписью - оба предназначены для модульного тестирования двух разных действий в одном API-контроллере. Один из этих тестовых примеров завершается неудачно с сообщением об ошибке в теме при вызове Mock<IHTTPClientFactory>.Verify(f => f.CreateClient(It.IsAny<String>()), Times.Once);
call. Странная вещь, это случается только с одним контрольным примером.
Ошибочный контрольный пример:
[Fact]
public async Task AddActionsToGroup_Post_Should_Return_NoActionsPerformedMessage_With_OK()
{
// Arrange - IHttpClientFactory
var httpClientFactory = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
var fixture = new Fixture();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(fixture.Create<NoActionsMessage>().ToString()),
});
var client = new HttpClient(mockHttpMessageHandler.Object);
client.BaseAddress = fixture.Create<Uri>();
httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
// Arrange - IOptions
var optionsMock = new Mock<IOptions<AppSettings>>();
optionsMock.SetupGet(o => o.Value).Returns(new AppSettings
{
LogicAppUri = "http://mocklogicappsuri",
ApiKey = "mockapikey",
AppBaseUri = "http://mockapobaseuri",
AppId = "mockappid",
AppSecret = "mockappsecret",
RefreshToken = "mockrefreshtoken"
});
// Arrange - ITokenProvider
var tokenProviderMock = new Mock<ITokenProvider>();
tokenProviderMock
.Setup(x => x.GetAccessTokenDetailsAsync())
.ReturnsAsync(new AccessToken
{
AccessToken = "mockaccesstokenresponse",
AccessTokenExpiry = 0,
EndpointUrl = new Uri("http://mockendpointuri"),
Scope = "mockscope"
});
// Arrange - CreateGroupEntity
AddActionEntity addActionEntity = new AddActionEntity();
// Act
var controller = new CommunicationController(httpClientFactory.Object, optionsMock.Object, tokenProviderMock.Object);
var result = await controller.AddActionsToGroup(addActionEntity);
// Assert
// IS FAILING with error message Expected invocation on the mock once, but was 0 times
httpClientFactory.Verify(f => f.CreateClient(It.IsAny<String>()), Times.Once);
Assert.NotNull(result);
Assert.IsAssignableFrom<OkObjectResult>(result);
Assert.IsAssignableFrom<NoActionsMessage>((result as OkObjectResult)?.Value);
Assert.False(String.IsNullOrWhiteSpace(((result as OkObjectResult)?.Value as NoActionsMessage)?.Message));
}
Проходной контрольный пример:
[Fact]
public async Task CreateGroup_Post_Should_Return_OK()
{
// Arrange - IHttpClientFactory
var httpClientFactory = new Mock<IHttpClientFactory>();
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
var fixture = new Fixture();
mockHttpMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(fixture.Create<String>()),
});
var client = new HttpClient(mockHttpMessageHandler.Object);
client.BaseAddress = fixture.Create<Uri>();
httpClientFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(client);
// Arrange - IOptions
var optionsMock = new Mock<IOptions<AppSettings>>();
optionsMock.SetupGet(o => o.Value).Returns(new AppSettings
{
LogicAppUri ="http://mocklogicappsuri",
ApiKey = "mockapikey",
AppBaseUri = "http://mockapobaseuri",
AppId = "mockappid",
AppSecret = "mockappsecret",
RefreshToken = "mockrefreshtoken"
});
// Arrange - ITokenProvider
var tokenProviderMock = new Mock<ITokenProvider>();
tokenProviderMock
.Setup(x => x.GetAccessTokenDetailsAsync())
.ReturnsAsync(new AccessToken
{
AccessToken = "mockaccesstokenresponse",
AccessTokenExpiry = 0,
EndpointUrl = new Uri("http://mockendpointuri"),
Scope = "mockscope"
});
// Arrange - CreateGroupEntity
CreateGroupEntity createGroupEntity = new CreateGroupEntity();
// Act
var controller = new CommunicationController(httpClientFactory.Object, optionsMock.Object, tokenProviderMock.Object);
var result = await controller.CreateGroup(createGroupEntity);
// Assert
httpClientFactory.Verify(f => f.CreateClient(It.IsAny<String>()), Times.Once);
Assert.NotNull(result);
Assert.IsAssignableFrom<OkObjectResult>(result);
Assert.IsAssignableFrom<String>((result as OkObjectResult)?.Value);
Assert.False(String.IsNullOrWhiteSpace((result as OkObjectResult)?.Value as String));
}
Может кто-нибудь сказать мне, кто я здесь неправильно.