简体   繁体   English

创建数据库连接错误NUnit C#

[英]Create database connection error NUnit c#

I'm developing an application in C# and I need to write unit tests for it. 我正在用C#开发应用程序,我需要为此编写单元测试。 One of the test requires the ability to handle exception when stuff like connection to database is lost/erroneous. 其中一项测试要求能够处理诸如与数据库的连接丢失/错误之类的异常。 What's the best practice to create such kind of error? 产生此类错误的最佳实践是什么? For example, changing connectionString at run time, etc. 例如,在运行时更改connectionString等。

I would recommend using a mocking framework to set-up your testable class (for example, a Repository with an Interface) to throw an error. 我建议使用模拟框架来设置您的可测试类(例如,带有接口的存储库)以引发错误。 For example, using Moq, you could do this in your unit test: 例如,使用Moq,您可以在单元测试中执行以下操作:

var mockRepo = new Mock<IRepository>();

mockRepo.Setup(x => x.GetCustomer(1))
        .Throws(new Exception("unable to connect to database"));

You can then Assert that the exception was thrown in your test. 然后,您可以断言测试中引发了异常。

Assert.Throws<Exception>(() => mockRepo.Object.GetCustomer(1));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM