如何模拟 DbConnectionStringBuilder?
How to mock DbConnectionStringBuilder?
这是一个重现异常的简单代码:
var csbMock = new Mock<DbConnectionStringBuilder>();
var csb = csbMock.Object;
csb.ConnectionString = "data source=.;integrated security=true";
Debug.WriteLine(csb.ConnectionString); // System.NullReferenceException in System.Data.dll
栈帧只有一行:at System.Data.Common.DbConnectionStringBuilder.get_ConnectionString()
我的目标是简单地能够 get/set DbConnectionStringBuilder.ConnectionString
属性 的 mock。这里有什么问题?
这一行解决了问题:
csbMock.CallBase = true;
DbConnectionStringBuilder.ConnectionString
setter 内部发生了一些神奇的事情。它调用被代理覆盖的虚拟成员,然后这个 NRE hapens in getter.
实际上没有必要模拟DbConnectionStringBuilder Class。
使用 class 没有连锁反应,因此您可以创建它的实例并按原样使用它
var builder = new DbConnectionStringBuilder();
//Set the connection string directly
builder.ConnectionString = "data source=.;integrated security=true";
//or add the parts needed to create a connection string
builder.Clear();
builder.Add("integrated security", true);
builder.Add("Data Source", ".");
这是一个重现异常的简单代码:
var csbMock = new Mock<DbConnectionStringBuilder>();
var csb = csbMock.Object;
csb.ConnectionString = "data source=.;integrated security=true";
Debug.WriteLine(csb.ConnectionString); // System.NullReferenceException in System.Data.dll
栈帧只有一行:at System.Data.Common.DbConnectionStringBuilder.get_ConnectionString()
我的目标是简单地能够 get/set DbConnectionStringBuilder.ConnectionString
属性 的 mock。这里有什么问题?
这一行解决了问题:
csbMock.CallBase = true;
DbConnectionStringBuilder.ConnectionString
setter 内部发生了一些神奇的事情。它调用被代理覆盖的虚拟成员,然后这个 NRE hapens in getter.
实际上没有必要模拟DbConnectionStringBuilder Class。
使用 class 没有连锁反应,因此您可以创建它的实例并按原样使用它
var builder = new DbConnectionStringBuilder();
//Set the connection string directly
builder.ConnectionString = "data source=.;integrated security=true";
//or add the parts needed to create a connection string
builder.Clear();
builder.Add("integrated security", true);
builder.Add("Data Source", ".");