嗨,我正在学习单元测试,我有两种方法可以更新并创建内容条目。该功能工作正常,但我不知道如何为此功能编写单元测试。
以下是更新条目的方法
public async Task UpdateEntryAsync(string contentTypeId, string entryId, int? version, string endpoint)
{
var entryRequest = await _httpClient.GetAsync($"{endpoint}/{entryId}");
var entryContent = await entryRequest.Content.ReadAsStringAsync();
dynamic getEntry = JsonConvert.DeserializeObject(entryContent);
//Update the PreviousSlug with current slug
getEntry.fields.previousSlug = getEntry.fields.slug;
var updatedEntryJson = JsonConvert.SerializeObject(getEntry);
var updatedEntryContent = new StringContent(updatedEntryJson, Encoding.UTF8, "application/json");
// Set headers for update request
updatedEntryContent.Headers.Add("X-Contentful-Content-Type", contentTypeId);
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());
await _httpClient.PutAsync($"{endpoint}/{entryId}", updatedEntryContent);
version++;
updatedEntryContent.Headers.Remove("X-Contentful-Version");
updatedEntryContent.Headers.Add("X-Contentful-Version", version.ToString());
await _httpClient.PutAsync($"{endpoint}/{entryId}/published", updatedEntryContent);
}
以下方法用于创建和发布:
public async Task CreateAndPublishRedirectEntryAsync(string entryId, string previousSlug,
string slug)
{
var endpoint = "entries";
var referenceEntry = new
{
sys = new { type = "Link", linkType = "Entry", id = entryId }
};
var fields = new RedirectionManager
{
PreviousSlug = new Dictionary<string, string> { { "en-GB", previousSlug } },
CurrentSlug = new Dictionary<string, string> { { "en-GB", slug } },
StatusCode = new Dictionary<string, int> { { "en-GB", 301 } },
CurrentArticle = new Dictionary<string, dynamic> { { "en-GB", referenceEntry } }
};
var redirectEntry = JsonConvert.SerializeObject(new { fields });
var content = new StringContent(redirectEntry, Encoding.UTF8, "application/json");
content.Headers.Add("X-Contentful-Content-Type", "redirectManager");
var redirectResponse = await _httpClient.PostAsync(endpoint, content);
var redirectResponseContent = await redirectResponse.Content.ReadAsStringAsync();
var entry = JsonConvert.DeserializeObject<ContentType>(redirectResponseContent);
if (!redirectResponse.IsSuccessStatusCode)
{
return;
}
await _httpClient.PutAsync(endpoint, content);
content.Headers.Add("X-Contentful-Version", "1");
await _httpClient.PutAsync($"{endpoint}/{entry.Sys.Id}/published", content);
}
我无法对其他答案添加评论,但是 github 的创建者在另一个答案上对mockhttp的使用有很好的描述 在单元测试中模拟 HttpClient