0

我对单元测试相当陌生。我有一个建立在 3 层架构中的站点,UI -> BLL -> DAL。而且我使用了 asp.net 提供程序模型,因此通过对 web.config 进行更改,我可以切换到 DAL dll 以针对不同的数据源,以完成使用实体框架编写的 DAL。

现在,我的问题是如何对我的 BLL 进行单元测试?我使用 NUnit。

如果运行/调试我的站点,asp.net/IIS 会加载所有内容并从 web.config 获取正确的配置,所以一切正常,因为入口点来自 IIS。现在,如果我使用 NUnit gui 进行测试并说我的测试项目“MySite.Test.dll”对我的 BLL 有测试用例,那么测试框架如何获得正确的配置以成功运行所有测试。它需要 web.config 中的信息来加载正确的提供程序!

现在,在我的 DAL 中有一个由 EntityFramework 创建的 App.config,其中只有 connectionString。我应该将所有与提供程序相关的配置都放在这个 app.config 中吗?还是我错过了一些关于如何正确执行此操作的大图?

这应该是我认为人们需要经常做的一件常见的事情。有人可以详细说明如何对我的库进行单元测试。

谢谢你,雷。


编辑:阅读前 2 个答案后,我认为我应该通过集成测试更正我的描述。基本上不是 IIS 作为入口点,而是使用 NUnit 之类的 GUI 工具来运行和测试我的代码,所以 NUnit -> BLL -> DAL。人们如何实际设置它?

谢谢,雷。

4

3 回答 3

1

Looks like what you are trying to do - is integration testing... Unit testing, by definition, testing Plain Old .Net Classes in isolation. No database, no configuration...so...as I see it, to do proper unit testing, you need to refactor your BLL to service layer and domain logic classes which you will test separately. Like: Service layer uses domain logic classes, and your unit test uses them. So, domain classes do not go to database, and you do not need connection strings and everything.

However, if you want to do proper integration testing with database, you might want to do that too. If this is what you need - google it, it's not difficult to get some configuration strings in nunit.config or something...I don't know the details.

However, I feel what you want to do is unit testing and not integration testing..

Ask yourself, WHAT EXACTLY DO I WANT TO TEST? Unit testing does not test "everything". Refactor, invert dependencies, and try to test you business logic in isolation.

于 2008-11-19T00:48:49.567 回答
1

您需要一个“MySite.Test.dll.config”文件,而不是单元测试项目中的“web.config”文件,而您可以在其中输入正确的测试配置。请注意,使用此方法,您可以根据需要使用不同的提供程序连接到内存数据库。

于 2009-04-15T11:22:00.560 回答
0

You have a couple of different options depending on how isolated you want to be from the DAL. If you want to involve the DAL in your tests, then you can copy the connection string section of the app.config file to an app.config file in your unit test project. As @badbadboy says, though, this really is integration testing, not unit testing.

If you want to do proper unit testing you probably want to use dependency injection and interfaces to allow you to mock out the DAL from your BLL. I use LINQ-to-SQL so what I do is create an interface and wrapper class around the DataContext. This allows me to create a mock database to use for unit testing to test my entity classes in isolation.

Testing your entity classes in isolation will make your tests less brittle and allow you to set up the data for each test independently. This makes it much easier to maintain.

You also might want to look into a mocking framework that will make it almost trivial to generate the mock objects. I've had pretty good success with Rhino Mocks, but there are others.

于 2008-11-19T01:02:00.523 回答