添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I'm new to unit testing, and trying to mock postContinent . But gives null and BadRequestObjectResult .

ContinentControllerTests

 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);

ContinentController

 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); }

ContinentService

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);}

Error:

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

The problem is in your Setup function. Reference types are equal only if you have overridden the equals function or if the are the exact same reference.

So by setting it up with the new keyword, it will never match the execution time object.

Try the It.IsAny<T> function from MOQ to verify.

Check the example here: 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());

Example. Apply to all setups.

_continentRepoMock
       .Setup(repo => repo.BestaatContinent(It.IsAny<Continent>()))
       .Returns(false);
                Hello @athanasios, thanks for the explanation. But I really don't know where to put it and how.
– Bataklik
                Jan 7, 2022 at 8:13
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.