c# - Moq 返回 null 和 BadRequestObjectResult

标签 c# asp.net api unit-testing moq

我是单元测试新手,并尝试模拟 postContinent。但给出了 nullBadRequestObjectResult

大陆 Controller 测试

 public class ContinentControllerTests {
 // RepoMocks
 private readonly Mock<IContinentRepository> _continentRepoMock = new Mock<IContinentRepository>();
 private readonly Mock<ICountryRepository> _countryRepoMock = new Mock<ICountryRepository>();
 private readonly Mock<ICityRepository> _cityRepoMock = new Mock<ICityRepository>();

 // Controller
 private readonly ContinentController _continentController;

     public ContinentControllerTests() {
     _continentServiceMock = new ContinentService(_continentRepoMock.Object);
     _continentController = new ContinentController(new ContinentService(_continentRepoMock.Object), new CountryService(_countryRepoMock.Object), new CityService(_cityRepoMock.Object));
     }
     [Fact]
     public void PostContinent_ValidInput_ReturnsCreateAtAction() {
     // Arrange
     _continentRepoMock
        .Setup(repo => repo.HeeftContinent("Test"))
        .Returns(false);
    _continentRepoMock
       .Setup(repo => repo.BestaatContinent(new Continent("Test", new List<Country>())))
       .Returns(false);
     _continentRepoMock
       .Setup(repo => repo.VoegContinentToe(new Continent("Test", new List<Country>())))
       .Returns(new Continent(1, "Test", new List<Country>()));
     // Act
     var response = _continentController.PostContinent(new ContinentInputDTO { Name = "Test" });

     // Assert
     Assert.IsType<CreatedAtActionResult>(response.Result);
     }
 }

大陆 Controller

 public class ContinentController : ControllerBase {
     private string _hostURL = $"http://localhost:5000/api/continent";
     private string _riverURL = $"http://localhost:5000/api/river";

     private ContinentService _continentService;
     private CountryService _countryService;
     private CityService _cityService;

     public ContinentController(ContinentService continentService, CountryService countryService, CityService cityService) {
         _continentService = continentService;
         _countryService = countryService;
         _cityService = cityService;
     }

     [HttpPost]
     public ActionResult<ContinentOutputDTO> PostContinent([FromBody] ContinentInputDTO continentDto) {
         try {
             if (_continentService.HeeftContinent(continentDto.Name)) { return BadRequest("Continent naam moet unique zijn!"); }
             var mappedContinent = MapToDomain.MapToContinentDomain(continentDto);
             Continent continent = _continentService.VoegContinentToe(mappedContinent);
             return CreatedAtAction(nameof(GetContinent), new { continentId = continent.Id },
             MapFromDomain.MapFromContinentDomain(_hostURL, continent));
         }
         catch (Exception ex) { return BadRequest(ex.Message); }
     }
 }

大陆服务

public class ContinentService {
     private readonly IContinentRepository _repo;
     public ContinentService(IContinentRepository repo) { _repo = repo;}

      public Continent VoegContinentToe(Continent c) {
         if (c == null) throw new ContinentServiceException("VoegContinentToe : continent is null");
         if (_repo.BestaatContinent(c)) throw new ContinentServiceException("VoegContinentToe : continent bestaat reeds");
         try {return _repo.VoegContinentToe(c);}
         catch (Exception ex) { throw new ContinentServiceException("VoegContinentToe: ", ex);}
    }
}

错误:

Message:  Assert.IsType() Failure
Expected: Microsoft.AspNetCore.Mvc.CreatedAtActionResult
Actual: Microsoft.AspNetCore.Mvc.BadRequestObjectResult

最佳答案

问题出在你的 Setup 上功能。仅当您重写了 equals 函数或者它们是完全相同的引用时,引用类型才相等。

因此,通过使用 new 关键字进行设置,它永远不会与执行时间对象匹配。

尝试It.IsAny<T>功能从最小起订量验证。

查看此处的示例:https://documentation.help/Moq/3CF54A74.htm

// Throws an exception for a call to Remove with any string value.
mock.Setup(x => x.Remove(It.IsAny<string>())).Throws(new InvalidOperationException());

示例。适用于所有设置。

_continentRepoMock
       .Setup(repo => repo.BestaatContinent(It.IsAny<Continent>()))
       .Returns(false);

关于c# - Moq 返回 null 和 BadRequestObjectResult,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70613855/

相关文章:

ios - 不工作 - 在 Swift 3/4 中以编程方式在 Api 中注册用户

api - 如何从Youtube音乐视频中提取艺术家和歌曲信息?

c# - 在 C# 中,如何将 DWORD 声明为 uint32?

c# - 在C#中从和弦中提取音符

c# - jQuery 模板忽略 String.Empty 值

c# - twitter 未经授权 401 c# oauth/request_token

c# - 注入(inject)需要对象取决于构造函数注入(inject)中的条件

c# - 在 Xamarin.Forms 中编写特定于设备平台的代码

javascript - 对话框中的按钮不会回发

javascript - 使用 jQuery 获取选定行的隐藏列的值