c# - MSTest 断言因空引用而失败

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

尝试为 .NET 4.7 Framework 项目创建一个简单的测试方法。所有示例均适用于 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" }
                };
        }
    }
}

最佳答案

您在第一个失败断言上的第一个错误说明了为什么这不起作用: locations 的类型是 OkNegotiatedContentResult<List<Location>> , 不是 OkNegotiatedContentResult<Location> .

由于您使用的是安全转换,as , 位置类型不是 OkNegotiatedContentResult<Location> ,转换的结果将始终为 null。

您可以按如下方式调整代码:

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

关于c# - MSTest 断言因空引用而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56031211/

相关文章:

c# - 从 C# 连接和使用 sqlite 数据库的最佳方法是什么

.net - 调试 WCF 时无法自动进入服务器

javascript - 在 React Jest/Enzyme 中测试子组件的条件渲染

unit-testing - VS2013 测试资源管理器替代方案

c# - 在 C# 和 WCF 中的线程之间共享对象

c# - 如何更改表单中所有控件上的文本语言

c# - 我如何检查一个字符串是否包含 C# 中的字符?

c# - "Item has already been added. Key in dictionary"的解决方法每次都使用相同的 key 但具有不同的值

c# - 开放实现的开放通用接口(interface)类型不等于接口(interface)类型?

python - 如何将 doctests 与 unittest 的测试发现相结合?