如何模拟SQL连接 [英] How to mock SQL connections

查看:66
本文介绍了如何模拟SQL连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 var connect = -keyword> new SqlConnection(_workFlowConnection))
{



如何在nunit单元测试中模拟上面的代码



我尝试过:



Mock< sqlconnection> sqlMock = new Mock< sqlconnection>();

sqlMock.Setup(a => a.ConnectionString).Returns();

解决方案

1)为您的数据层设置一个接口

2)让您的数据层实现该接口(或者如果您已准备好数据层,则提取接口)

3)现在你可以为界面设置模拟



  public   interface  IDataLayerMyApp 
{
IEnumerable< string> GetMachineType( string werk);
}


public class DataLayerMyApp:IDataLayerMyApp
{
public IEnumerable< string> GetMachineType( string werk)
{
IEnumerable< string>结果;
使用 var connection = new SqlConnection(ConnectionString))
{
connection.Open();
// 在这里工作
}
返回结果;
}
}


[测试]
public void TheTestFunc()
{
// 安排
var dal = new Mock< IDataLayerMyApp>();
List< string> yourResult = ...
dal.Setup(m = > m.GetMachineType(It.IsAny< string>()))
。返回(yourResult)
}


using (var connect = new SqlConnection(_workFlowConnection))
              {


how to mock the above code in nunit unit testing

What I have tried:

Mock<sqlconnection> sqlMock=new Mock<sqlconnection>();
sqlMock.Setup(a => a.ConnectionString).Returns("");

解决方案

1) set up an interface for your datalayer
2) let your datalayer implement that interface (or extract the interface if you already have the datalayer ready)
3) now you can setup the mock for the interface

public interface IDataLayerMyApp
{
   IEnumerable<string> GetMachineType(string werk);
}


public class DataLayerMyApp : IDataLayerMyApp
{
  public IEnumerable<string> GetMachineType(string werk)
  {
    IEnumerable<string> result;
    using (var connection = new SqlConnection(ConnectionString))
    {
      connection.Open();
      // do your work here
    }
    return result;
  }
}


[Test]
public void TheTestFunc()
{
   //Arrange
   var dal = new Mock<IDataLayerMyApp>();
   List<string> yourResult = ...
   dal.Setup(m => m.GetMachineType(It.IsAny<string>()))
      .Returns(yourResult)
}


这篇关于如何模拟SQL连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆