0

I'm trying to stub this:

public T GetCommand<T>() where T : ICommand, new()

I'm using Moq (C#), and my code looks like this:

_mockedBusinessFactory.Setup(x => x.GetCommand<ICommand>());

But there is a question: how to deal with the new() constraint?

Any idea?

Nico
  • 255
  • 2
  • 12
  • I guess ICommand is an interface? If so you should mock out that interface and then `_mockedBusinessFactory.Setup(x => x.GetCommand());` – Jamie Rees Jul 27 '15 at 11:57
  • Can you finish the line, what do you want to set it up to do? – weston Jul 27 '15 at 12:07
  • Also how would you use this, because `_factory.GetCommand()` isn't valid, as the `T` must be newable. – weston Jul 27 '15 at 12:11
  • GetCommand is a method? Methods do not have new() constraint or am i missing something? – Daniel Dušek Jul 27 '15 at 13:38
  • Yes, GetCommand is a method, and the ", new()" constraint mean that the provided T element must have a public ctor. Jamie, you wanna mock an interface? Do I miss something? I already try your syntax. @welton: this is classified code, I can't past more than that. – Nico Jul 27 '15 at 15:22
  • 1
    Do you not know what `T` is going to be when the mock is used? Or is that `T` not accessible from your scope? Related thread: [Mocking generic methods in Moq without specifying T](http://stackoverflow.com/questions/20072429/). Also: [Mocking generic method call for any given type parameter](http://stackoverflow.com/questions/5311023/). – Jeppe Stig Nielsen Jul 27 '15 at 22:57

1 Answers1

0

Maybe something like this:

var stub = new Mock<ICommand>();
stub.Setup( //... setup stub

mockedBusinessFactory.Setup(x => x.GetCommand<ICommand>()).Returns(stub.Object);

PS. I'm not moq user

Piotr Pasieka
  • 2,063
  • 1
  • 12
  • 14