3 Replies
I'm currently learning unit tests and need to know how to write test for the following method. It doesn't return anything just doing a action. How to asset that. I'm clueless on this one.
@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);
}
}
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
Methods that don't return anything are hard to test and you have more or less no option but to use mocking/fakes to just verify that it calls the expected methods. Nuthanms code above does this, even thou the actual assertions seem wrong at a glance