使用mock进行单元测试

时间:2017-03-30 05:58:25

标签: c# json unit-testing

我正在尝试对我的应用进行单元测试。 这是我的考验:

class CustomerControllerTest
{
    [Test]
    public void GetAuctionsByJson_works()
    {
        // Arrange
        Mock<IAuctionRespository> mockAuction = new Mock<IAuctionRespository>();
        mockAuction.Setup(m => m.Auctions).Returns(new Auction[]
            {
                new Auction { a_id=1, auctionname="computer", deadLine=DateTime.Today},
                new Auction { a_id=2, auctionname="keyboard", deadLine=DateTime.Today},
                new Auction { a_id=3, auctionname="mouse", deadLine=DateTime.Today}
            }.AsQueryable());
        CustomerController controller = new CustomerController(mockAuction.Object);
        var actual = controller.GetAuctionsByJson() as JsonResult;
        //parse result
        List<Auction> result = actual.Data as List<Auction>; //null
        Assert.AreEqual(3, result.Count);
        Assert.AreEqual(1, result[0].a_id);
        Assert.AreEqual("computer", result[0].auctionname);
        Assert.AreEqual(DateTime.Today, result[0].deadLine);

    }
}

var actual有值(如图所示) actual val 但我得到的var结果为null result val 为什么? 我怎样才能在列表中获得实际值? 感谢

1 个答案:

答案 0 :(得分:0)

谢谢安德烈!我的解决方案是添加以下内容:

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Auction> result = serializer.Deserialize<List<Auction>>(serializer.Serialize(actual.Data));