How To use NUnit DynamicMock to mock non-Interface and non-MarshalByRef

依然范特西╮ 提交于 2019-12-12 02:48:13

问题


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*/

Edit #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);

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.

Edit #2 This seems to be a problem for a lot of people The target is to create a mock directly from the socket.


回答1:


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.

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 isn't very well documented and represented in internet it appears, but I took a look here into code from its constructor

http://nunit.sourcearchive.com/documentation/2.5.10.11092plus-pdfsg-1/DynamicMock_8cs_source.html#l00014

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.




回答2:


I resolved my issue.

The answer is DynamicMock just with Interfaces.

Moq just with prosperparameters or, since i want it easy a lot of times - here is what i did:

public class Test_MockSocket : Socket
{
    public Test_MockSocket() : base (
                    (new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30000)).AddressFamily,
                    (SocketType.Stream),
                    (ProtocolType.Tcp))
    {
    }
}

And when setting up the test:

        var Mock = new Mock<Test_MockSocket>();
        Socket MockSocket = (Socket)Mock.Object;
        ToBeTested Actual = new ToBeTested (MockSocket);

i can not think you can get it with less effort than this.



来源:https://stackoverflow.com/questions/7394013/how-to-use-nunit-dynamicmock-to-mock-non-interface-and-non-marshalbyref

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!