【发布时间】:2011-05-13 11:40:52
【问题描述】:
我目前正在处理继承的代码库。缺少的关键部分之一是单元测试。在尝试在 NUnit 中设置一些单元测试时,我似乎遇到了障碍。
我像往常一样创建了一个单独的单元测试项目,添加了对 SubSonic、NUnit 和应用程序创建的各种 DLL 的必要引用,并设置了一个虚拟单元测试以确保一切设置正确。当我尝试引用 SubSonic 生成的一些对象时,问题就开始了。我创建了这个测试来列出用户:
[Test]
public void CanListUsers()
{
UserCollection users = UserController.List(UserController
.Query()
.Where(User.Columns.IsDeleted, false));
Assert.IsNotNull(users);
}
得到了这个异常:
在您的系统中找不到 SubSonicService 应用程序的配置
我通过将与 SubSonic 相关的 Web.config 部分提取到单元测试项目中的 App.config 中来解决此问题。现在,当我重新运行单元测试时,我得到:
UnitTests.TestClass.CanListUsers: System.Reflection.TargetInvocationException : 异常已被 调用的目标。 ----> System.Configuration.ConfigurationErrorsException : 无法加载类型 'Utility.SqlSubsonicProvider' 来自 程序集'System.Web,版本= 4.0.0.0, 文化=中性, PublicKeyToken=b03f5f7f11d50a3a'。
这个异常让我很困惑,因为 SqlSubsonicProvider 是 Utility 命名空间中的一个类,可以在对象浏览器中看到,那么为什么要在 System.Web 中查找它?
编辑:好的,我重新排列了解决方案中的命名空间,使它们更有意义。我认为这解决了上述错误。不幸的是,我现在遇到了这个错误:
ChannelMechanics.UnitTests.TestClass.CanListVendors:
System.Reflection.TargetInvocationException : Exception has been thrown by the target
of an invocation.
----> System.NullReferenceException : Object reference not set to an instance of
an object.
更奇怪的是,当我在“调试”菜单中使用 Visual Studio 的“附加到进程”命令并附加到 NUnit GUI 时,单元测试通过了。我的理论是从调试器中很容易发现空对象。
如果有帮助,我的 App.config 如下所示:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="SubSonicService"
type="SubSonic.SubSonicSection, SubSonic"
requirePermission="false"/>
</configSections>
<connectionStrings>
<add name="DatabaseConnection"
connectionString="*removed*"/>
</connectionStrings>
<SubSonicService defaultProvider="TestProvider">
<providers>
<clear />
<add name="TestProvider"
type="SubSonic.SqlDataProvider, SubSonic"
connectionStringName="DatabaseConnection"
generatedNamespace="Test"/>
</providers>
</SubSonicService>
</configuration>
异常详情如下:
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type,
Boolean publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis,
Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance[T]()
at SubSonic.ActiveController`2.Query()
at UnitTests.TestClass.CanListVendors() in UnitTests\TestClass.cs:line 59
--NullReferenceException
at DataAccess.Vendor.GetTableSchema() in DataAccess\Generated\Models\Vendor.cs:line 376
at DataAccess.Vendor.SetSQLProps() in DataAccess\Generated\Models\Vendor.cs:line 42
at DataAccess.Vendor..ctor() in DataAccess\Generated\Models\Vendor.cs:line 35
我正在运行的测试与上面列出的测试基本相同,只是应该列出的是供应商而不是用户。
[Test]
public void CanListVendors()
{
VendorCollection vendors = VendorController.List(
VendorController
.Query()
.Where(Vendor.Columns.IsDeleted, false));
Assert.IsNotNull(vendors);
}
【问题讨论】:
标签: unit-testing nunit subsonic