如何使用NUnit DynamicMock模拟非接口和非MarshalByRef [英] How To use NUnit DynamicMock to mock non-Interface and non-MarshalByRef
问题描述
i am writing a Class wich will be initialised with a Socket. I want to write a Test using an NUnit DynamicMock.
如何创建套接字不需要太多的努力?
How can i create a Mock of the Socket without much effort?
DynamicMock DynamicSocketMock = new DynamicMock(typeof (Socket));
/*No ERROR - BUT I THINK HERE IS THE PROBLEM*/
Socket SocketMock = (Socket) DynamicSocketMock.MockInstance;
/*RUNTIME ERROR*/
ToBeTested Actual = new ToBeTested(SocketMock);
/*NEVER REACHED*/
编辑#1
我看了起订量,看起来还不错,但是我仍然无法测试.我最初的问题是找到要使用的严格版本,但我想我已经解决了.
I looked into moq nad it looks quite nice however i still can not test. My initial Problem was to find the rigth version to use, but i think i solved this.
var Mock = new Mock<Socket>();
Socket MockSocket = (Socket)Mock.Object;
ToBeTested Actual = new ToBeTested(SocketMock);
问题在于Socket不具有没有参数的构造函数.现在我不想给它一个参数,我想模拟一切.
The Problem ist that Socket does not feature a Constructor without parameters. Now i do not want to give it a parameter, i want to mock everything.
编辑#2 对于很多人来说,这似乎是一个问题目标是直接从套接字创建一个模拟.
Edit #2 This seems to be a problem for a lot of people The target is to create a mock directly from the socket.
推荐答案
我认为模拟Socket
是一项相当高级的任务,NUnit DynamicMock不适合这样做,毕竟它们并不假装是真正强大的模拟解决方案.
I think mocking Socket
is a fairly advanced task NUnit DynamicMock isn't suited for that, after all they don't pretend to be a real powerful mocking solution.
我个人使用的是Moq,由于Socket类未密封,因此我认为使用Moq对其进行模拟应该非常简单并且适合您的需求.
I am personally using Moq, and since Socket class isn't sealed I think mocking it with Moq should be pretty straightforward and suitable for your needs.
Nunit DynamicMock的文档并没有很好地记录在互联网上,但我在这里从其构造函数中了解了代码
Nunit DynamicMock isn't very well documented and represented in internet it appears, but I took a look here into code from its constructor
看起来除了接口之外,它不应该与其他任何东西一起使用,因此一旦需要,您就需要研究真正的模拟框架.
looks like it isn't supposed to work with anything except interfaces, so you need to look into real mock framework once you need that.
这篇关于如何使用NUnit DynamicMock模拟非接口和非MarshalByRef的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!