0

I have the following:

public interface IAction
{
   void Do(string a, int b = 0);
}

public class A : IAction
{
     public void Do(string a, int b = 0)
     {
         // work is done
     }
}
public class B
{
     private readonly IAction _a;
     public B(IAction a) //assume IOC is configured to inject an instance of B 
     {
       _a = a;
     }

     //this is the method i want to test.
     public void DoStuff(string arg)
     {
       //I am calling Do() with ONLY ONE parameter - because the other is optional
       _a.Do(arg); 
       //do something else - optional
     }
}

And my test looks something like this:

[TestClass]
 public class BTest
 {
    [TestMethod]
    public void DoStuffShouldBlablaForValidInput()
    { 
       Mock<IAction> _mockedB = new Mock<IAction>(MockBehavior.Strict);
       var b = new B(_mockedB.Object);
       _mockedB .Setup(x => x.Do(It.IsAny<string())).Verifiable();
       b.DoStuff("sample");       
       // verify that Do() was called once
       _mockedB.Verify(x => x.Do(It.IsAny<string()), Times.Once); 
    }
 }

But I'm getting: "An expression cannot contain a call or invocation that uses optional argument" error on this line"_mockedB .Setup(x => x.Do(It.Any x.Do(It.IsAny

How do i fix this without requiring method DoStuff() to pass the optional parameter as well for method Do()?

Thanks,

user3818435
  • 707
  • 2
  • 9
  • 16
  • 1
    From here: http://stackoverflow.com/questions/12957537/how-do-i-moq-a-method-that-has-an-optional-argument-in-its-signature-without-exp Looks like you will HAVE to specify the second parameter. – zaitsman Aug 05 '14 at 00:04
  • 1
    I don't think it's possible, as you can see in [this question](http://stackoverflow.com/questions/12957537/how-do-i-moq-a-method-that-has-an-optional-argument-in-its-signature-without-exp). Also your code snippet don't compile, B does not implements IAction methods and It.Any does not exists (in recent versions, at least), it's It.IsAny. – Pierre-Luc Pineault Aug 05 '14 at 00:04
  • I saw that but it didn't work. What is in the else statement? The if part is passing all parameters and that is not a problem. Its now marked as "duplicate" but its because that answer didn't answer the problem (in my case) and I can't rephrase it more. I specifically explained the code piece plus the the error and on which line. Can you please remove the "mark as duplicate" so that I can get the help? – user3818435 Aug 05 '14 at 19:32

0 Answers0