Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
293 views
in Technique[技术] by (71.8m points)

.net - Easy way to mock a WCF service?

I've got an app which is using a WCF service. Now I'd like to add unit tests to the app.

For some cases I need to mock the WCF service, since getting the desired behaviour from the service sometimes is tough (e.g. service throws special exceptions).

I could add yet another interface to the wcf client, but this seems a bit silly, since the client calls already are using an interface.

Is there an easy way to mock a WCF service? Easier than creating another interface layer and redirecting every single WCF call inside it?

Edit: Most of the answers seem not to know much about WCF service using, so some clarification:
To use a WCF service from a ViewModel, I have to manage the connection something like this:

ChannelFactory<IMyWcfService> channelFactory = new ChannelFactory<IMyWcfService>("");
IMyWcfService proxy = channelFactory.CreateChannel();
proxy.CallMyStuff();
proxy.Close();

I can't just pass the ViewModel the proxy to the WCF, since the connection needs to be opened and closed for every transaction. For this reason using RhinoMock/NMock would not work, since they need a ViewModel which gets the proxy as a parameter, which can't be done like this if you use WCF.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Why can't you use something like NMock2 to mock the IMyWcfService interfaces directly?

If you need to be able to create new instances on the fly, use the Factory to hide the ChannelFactory<IMyWcfService> from the client. This way you can replace the factory, providing the client one which creates mocks instead of real proxies.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...