nuthanm
Need help on how to write unit tests in xunit for the code
Here I used MOQ library to complete this. We don’t perform actual http call but we configured or setup the response so that it mimics the call and take the defined response and process it. Hope you understand this
5 replies
Need help on how to write unit tests in xunit for the code
@Raki - please find the below code and hope it solves your problem. [Fact]
public async Task UpdateEntryAsync_ShouldUpdateAndPublish()
{
// Arrange
var contentTypeId = "your_content_type_id";
var entryId = "your_entry_id";
var version = 1; // replace with your actual value
var endpoint = "your_api_endpoint"; // you can give any dummy here
var httpClientMock = new Mock<IHttpClient>();
var entryService = new EntryService(httpClientMock.Object);
// Mocking the response when fetching the entry
var entryResponseContent = @"{
'fields': {
'slug': 'new-slug',
'previousSlug': 'old-slug'
}
}";
httpClientMock.Setup(client => client.GetAsync($"{endpoint}/{entryId}"))
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(entryResponseContent, Encoding.UTF8, "application/json")
});
// Act
await entryService.UpdateEntryAsync(contentTypeId, entryId, version, endpoint);
// Assert
httpClientMock.Verify(client => client.PutAsync($"{endpoint}/{entryId}", It.IsAny<StringContent>()), Times.Exactly(2));
httpClientMock.Verify(client => client.PutAsync($"{endpoint}/{entryId}/published", It.IsAny<StringContent>()), Times.Once);
}
}
5 replies