MSTest断言失败,引用为空

时间:2019-05-07 22:25:44

标签: c# .net unit-testing mstest .net-framework-version

尝试为.NET 4.7 Framework项目创建简单的测试方法。所有示例均适用于Core或更早版本的MSTest框架。

我可以通过对返回对象的简单检查来使测试通过。如果我尝试更复杂的操作(例如验证返回的记录数),则测试将失败,因为contentResult始终显示为null。

我指出了哪些断言失败。

using Locations.Api.Controllers;
using Locations.Api.Domain.Models;
using Locations.Api.Domain.Services.Interfaces;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Collections.Generic;
using System.Web.Http;
using System.Web.Http.Results;

namespace Locations.Api.Tests
{
    [TestClass]
    public class TestLocationsController
    {
        [TestMethod]
        public void GetAllLocations_ShouldReturnAllLocations()
        {
            // Arrange
            List<Location> testLocations = GetTestLocations();

            Mock<ILocationsService> locationsServiceMock = new Mock<ILocationsService>();
            locationsServiceMock.Setup(location => location.GetAllLocations())
                        .Returns(testLocations);

            LocationsController controller = new LocationsController(locationsServiceMock.Object);

            // Act
            IHttpActionResult locations = controller.GetAllLocations();

            // Assert
            Assert.IsNotNull(locations, "locations is null");
            var contentResult = locations as OkNegotiatedContentResult<Location>;

            // THESE ALL FAIL
            Assert.IsInstanceOfType(locations, typeof(List<Location>), "Wrong Model");      // ERROR: type:<System.Collections.Generic.List`1[Locations.Api.Domain.Models.Location]>. Actual type:<System.Web.Http.Results.OkNegotiatedContentResult`1[System.Collections.Generic.List`1[Locations.Api.Domain.Models.Location]]>.

            Assert.IsNotNull(contentResult.Content, "contentResult is null");           // ERROR: System.NullReferenceException
            Assert.AreEqual(1, contentResult.Content.Id);                               // ERROR:  System.NullReferenceException
            Assert.AreEqual(2, locations.Count(), "Got wrong number of locations");     //  ERROR:  'IHttpActionResult' does not contain a definition for 'Count'
        }


        private static List<Location> GetTestLocations()
        {
            return new List<Location> {
                    new Location { Id = 1, Name = "Albuquerque", Category = "Terminal", Street = "301 Airport Road NW", City = "Albuquerque", State = "NM", ZipCode = "87121", Latitude = 35.0822720000M, Longitude = -106.7169960000M, NearestMajorCity = "Albuquerque", Phone1 = "(505) 344-1619", Phone2 = null, Avaya = null, GateCode = "1234", SpecificEntranceDirections = "Enter via front gate", SwiftCharitiesAmbassador = "Homer Simpson", Extras = "stuff" },
                    new Location { Id = 2, Name = "Columbus", Category = "Terminal", Street = "4141 Parkwest Drive", City = "Columbus", State = "OH", ZipCode = "43228", Latitude = 39.9668110000M, Longitude = -83.1153610000M, NearestMajorCity = "Cincinnati", Phone1 = "(614) 274-5204", Phone2 = null, Avaya = null, GateCode = "5678", SpecificEntranceDirections = "Enter on west side", SwiftCharitiesAmbassador = "Marge Simpson", Extras = "none" }
                };
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您对第一个失败的断言的第一个错误说明了为什么它不起作用: 位置类型为OkNegotiatedContentResult<List<Location>>,而不是OkNegotiatedContentResult<Location>

由于您使用的是安全的强制转换as,并且位置类型不是OkNegotiatedContentResult<Location>,因此强制转换的结果将始终为空。

您可以如下调整代码:

var contentResult = locations as OkNegotiatedContentResult<List<Location>>;

Assert.IsNotNull(contentResult, "contentResult should not be null.");
Assert.IsInstanceOfType(contentResult.Content, typeof(List<Location>), "Wrong Model");      
Assert.IsNotNull(contentResult.Content, "contentResult.Content is null");           
Assert.AreEqual(1, contentResult.Content[0].Id);                               
Assert.AreEqual(2, contentResult.Content.Count, "Got wrong number of locations");