测试无法在数据库中模拟插入

时间:2019-04-23 07:59:18

标签: c# .net-core mocking

请找到项目源的链接:https://bitbucket.org/danchi/salescheese/src/master/

我在测试一个域实体时遇到问题

public class RegisterStockUseCaseUnitTests
    {
        [Fact]
        public async void Can_Register_Stock()
        {


            //arrange
            var mockProductRepository = new Mock<IProductRepository>();
            var mockStockRepository = new Mock<IStockRepository>();
            var mockUserRepository = new Mock<IUserRepository>();
            var mockStorageLocationRepository = new Mock<IStorageLocationRepository>();

            mockProductRepository.Setup(repo => repo.FindById(It.IsAny<int>()))
                .Returns(Task.FromResult(true));

            mockUserRepository.Setup(repo => repo.FindById(It.IsAny<string>()))
                .Returns(Task.FromResult(true));

            mockStorageLocationRepository.Setup(repo => repo.FindById(It.IsAny<int>()))
                .Returns(Task.FromResult(true));

            var useCase = new RegisterStockUseCase(mockStockRepository.Object,mockProductRepository.Object,mockUserRepository.Object, mockStorageLocationRepository.Object);

            var mockOutputPort = new Mock<IOutputPort<RegisterStockResponse>>();

            mockOutputPort.Setup(outputPort => outputPort.Handle(It.IsAny<RegisterStockResponse>()));


            //act
            var response =
                await useCase.Handle(new RegisterStockRequest(5, "userId", StockType.Output, UnitOfMeasure.Grams,10,1),
                    mockOutputPort.Object);

            //assert
            Assert.True(response);

        }
    }

当我调试时,我得到: System.NullReferenceException:'对象引用未设置为对象的实例。' 我不知道是什么,你能帮我吗? 附言任何想法如何改进测试是受欢迎的。它们都是用TDD创建的。 谢谢

[更新1] enter image description here

1 个答案:

答案 0 :(得分:0)

我忘了设置用于创建股票的模拟功能,所以我错过了代码的下一部分

    mockStockRepository.Setup(repo => repo.Create(It.IsAny<Stock>()))
        .Returns(Task.FromResult(new CreateStockResponse(1, true)));