用于检查的TestMethod如果将对象成功添加到表中

问题描述 投票:1回答:1

到目前为止我有这个:

 using (var actContext = new ItsAllAboutTheGameDbContext(contextOptions))
        {
            var cardService = new CardService(actContext);
            creditCardResult = await cardService.AddCard("3242423532532434", "332", DateTime.Parse("02.03.2020"), user);
            actContext.CreditCards.Add(creditCardResult);
            await actContext.SaveChangesAsync();


        }

        //Assert

在上下文中将卡添加到CreditCards表后,如果成功添加,我该如何断言?我需要检查它是否被添加到内存数据库中(行为上下文)?

.net sql-server unit-testing async-await
1个回答
1
投票

你真的想断言数据是否插入表中?

您应该将DBContext工厂注入您的控制器,并在您的单元测试中使用假工厂。

public class MyController:Controller {public MyController(Func dbContextFactory)...

...

    using (var actContext = dbContextFactory())

}

然后,在您的测试中,您只需将工厂注入模拟上下文。

更好的是,在控制器中注入一个组件。

否则,您将离开查询数据库以查看数据是否存在。

© www.soinside.com 2019 - 2024. All rights reserved.