C# n替代模拟AS/IS.net
我很难模仿C# n替代模拟AS/IS.net,c#,.net,mocking,npgsql,nsubstitute,C#,.net,Mocking,Npgsql,Nsubstitute,我很难模仿IDbConnection。我有一个返回IDbConnection的方法,但是我有一个检查来验证这个连接是否是NpgsqlConnection,如下所示: if (conn as NpgsqlConnection == null) { throw new System.Exception("error"); } var testConnection = new NpgsqlConnection("TESTCONNECTIONSTRING"
IDbConnection
。我有一个返回IDbConnection
的方法,但是我有一个检查来验证这个连接是否是NpgsqlConnection
,如下所示:
if (conn as NpgsqlConnection == null)
{
throw new System.Exception("error");
}
var testConnection = new NpgsqlConnection("TESTCONNECTIONSTRING");
var conn = Substitute.For<ConnectionManager>();
conn.GetConnection().Returns(testConnection);
当方法返回mock对象时,强制转换(as
)返回null并创建异常。如何使用NSubsiute,使其将其视为NpgsqlConnection
对象
接下来的第二个问题是,如果这个问题可以解决的话,我使用的是
BeginBinaryImport
fromNpgsqlConnection
,它没有接口,我不能模拟它,我怎么能伪造它,这样当使用var importer=conn.BeginBinaryImport像这样使用时,它就不会抛出错误(“复制…”?这取决于实际要测试的内容。如果要测试NpgsqlConnection
的功能,还可以使用测试连接字符串创建NpgsqlConnection
public void DoSomething()
{
// returns NpgsqlConnection with test connection string
// If you substituted for a class rather than an interface, check that the call to your substitute was on a virtual/abstract member.
IDbConnection conn = _connectionManager.GetConnection();
if (conn as NpgsqlConnection == null)
{
throw new System.Exception("error");
}
// functionality
using (var writer = (conn as NpgsqlConnection).BeginBinaryImport("COPY data (field_text, field_int4) FROM STDIN BINARY"))
{
// do some stuff
}
}
这里。您可以使\u connectionManager.GetConnection();
返回一个测试数据库连接,它是NpgsqlConnection。因此您可以测试代码
您可以这样设置:
if (conn as NpgsqlConnection == null)
{
throw new System.Exception("error");
}
var testConnection = new NpgsqlConnection("TESTCONNECTIONSTRING");
var conn = Substitute.For<ConnectionManager>();
conn.GetConnection().Returns(testConnection);
在这里,您可以模拟\u npgsqlConnectionHelper