简体   繁体   English

如何模拟OracleConnection和OracleCommand?

[英]How can I mock an OracleConnection and OracleCommand?

For my tests I need to mock out the data client, in my case they are Oracle. 对于我的测试,我需要模拟数据客户端,在我的例子中,他们是Oracle。

I have created my data access layer to allow this to be passed in: 我创建了我的数据访问层以允许传入:

public static Int32? GetUserRoleId(string userName, OracleConnection cn, OracleCommand cmd)

I am using Moq, though I can switch to another framework if needed, and when I go to create the Mock objects like this: 我正在使用Moq,虽然我可以根据需要切换到另一个框架,当我去创建像这样的Mock对象时:

Mock<OracleConnection> mockOracleConnection = new Mock<OracleConnection>();
Mock<OracleCommand> mockOracleCommand = new Mock<OracleCommand>();

I get this error: 我收到此错误:

Failure: System.ArgumentException : Type to mock must be an interface or an abstract or non-sealed class. 失败:System.ArgumentException:类型为mock必须是接口或抽象或非密封类。

Conclusion: This was more simple than I thought! 结论:这比我想象的更简单! Just mock the DAL layer function like this: 只需像这样模拟DAL层函数:

mockDao.Setup(a => a.GetUserRoleId(userName, It.IsAny<OracleConnection>(), It.IsAny<OracleCommand>())).Returns(1);

You can make changes to use IDbConnection and IDbCommand (use interfaces and have a factory to provide the real objects in main code and mock objects in test - normally using Dependency Injection) 您可以进行更改以使用IDbConnection和IDbCommand(使用接口并使用工厂在主代码中提供真实对象并在测试中提供模拟对象 - 通常使用依赖注入)

Moq can only mock Interfaces and virtual methods. Moq只能模拟接口和虚拟方法。

You're trying to mock a sealed class: you can look at here . 你正试图嘲笑一个密封的课:你可以看看这里

BTW: As @Aliostad said , such framework - most mock frameworks I've seen too - can mock only Interfaces/Abstract classes. BTW:正如@Aliostad 所说 ,这样的框架 - 我见过的大多数模拟框架 - 都只能模拟Interfaces / Abstract类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM