[英]How to test async Task<IActionResult> returning IEnumerable<model> using moq in xunit?
[英]xUnit test using Moq for Task<IActionResult> type method
我是 Moq 框架的新手。 在這里,我正在嘗試為 mvc 項目中的以下方法編寫一個簡單的 xUnit 測試。 在示例代碼的最后一部分,我添加了我的 xUnit 測試方法,但我不知道如何設置commandMock.Setup
。 知道我應該在上面設置什么嗎?
在此方法上編寫的 xUnit 測試:
public async Task<IActionResult> Save(UpdateTermsAndConditionCommand command)
{
var response = await Mediator.Send(command);
return response.Success ? this.SuccessSaveResult(response.Message) : this.FailSaveResult(CommonResources.msgErrorSomthingWentWrong);
}
更新條款和條件命令 class:
public class UpdateTermsAndConditionCommand : IRequest<ResponseDetail>
{
public long Id { get; set; }
[Display(Name = "labelEnglishTermsAndCondition", ResourceType = typeof(TermsAndConditionResources))]
[XSSIgnore]
[Required(ErrorMessageResourceName = "msgEnglishTermsConditionRequire", ErrorMessageResourceType = typeof(TermsAndConditionResources))]
public string EngTermsAndCondition { get; set; }
[Display(Name = "labelDutchTermsAndCondition", ResourceType = typeof(TermsAndConditionResources))]
[XSSIgnore]
[Required(ErrorMessageResourceName = "msgDutchTermsConditionRequire", ErrorMessageResourceType = typeof(TermsAndConditionResources))]
public string DutchTermsAndCondition { get; set; }
[Display(Name = "labelGermanTermsAndCondition", ResourceType = typeof(TermsAndConditionResources))]
[XSSIgnore]
[Required(ErrorMessageResourceName = "msgGermanTermsConditionRequire", ErrorMessageResourceType = typeof(TermsAndConditionResources))]
public string GermanTermsAndCondition { get; set; }
}
調解員class:
[XSSFilter]
public abstract class BaseController<T> : Controller
{
private ISender _mediator;
private ILogger<T> _logger;
protected ISender Mediator => _mediator ??= HttpContext.RequestServices.GetService<ISender>();
protected ILogger<T> Logger => _logger ??= HttpContext.RequestServices.GetService<ILogger<T>>();
[HttpPost]
public ActionResult Pdf_Export_Save(string contentType, string base64, string fileName)
{
var fileContents = Convert.FromBase64String(base64);
return File(fileContents, contentType, fileName);
}
public async Task<List<LanguageListItemDto>> GetLanguages()
{
var response = await Mediator.Send(new GetLanguageListQuery());
return response.Languages;
}
}
使用最小起訂量的 xUnit 測試:
[Fact]
public void SaveXUnit()
{
//arrange
var commandMock = new Mock<UpdateTermsAndConditionCommand>();
var controller = new TermsandConditionController();
commandMock.Setup(x => x.Execute());//here i am not getting idea how to setup the command
//act
//assert
}
UpdateTermsAndConditionCommand
是一個class
,您可以實例化它 ( var command = new UpdateTermsAndConditionCommand { }
) 並且不能被模擬。
只能abstract classes
和interfaces
。
最簡單的方法是在你想要測試和模擬這些的class
注入依賴。 您可以先閱讀依賴注入
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.