0

I'm implementing the quickstart features of Moq as a learning exercise by creating a simple console application. When I run the app I see the exception.

class Foo : IFoo
{
    public bool DoSomething(string value)
    {
        return false;
    }
}

public class Program
{
    private static Mock<IFoo> mock = new Mock<IFoo>();

    static void Main(string[] args)
    {
      mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>();
      Assert.That(() => mock.Object.DoSomething("reset"), 
          Throws.InvalidOperationException);
    }
}
2
  • 1
    Your class Foo does not have any dependencies... so you don't need to mock anything to test that class. You should simply create object of Foo by doing var foo = new Foo(); Commented Feb 28, 2021 at 6:54
  • What do you do here? Are you mocking the System Under Test? What do you really want to test? Commented Mar 1, 2021 at 8:01

2 Answers 2

1

This does not look like a Moq problem, more a I can't catch the exception thrown in DoSomething problem. I will assume that you use the nunit framework.

Try to use the built in method Assert.Throws for exception assertion

Assert.Throws<InvalidOperationException>(
      () => { mock.Object.DoSomething("reset"); });
Sign up to request clarification or add additional context in comments.

Comments

0

It looks like if you run unit tests as part of an application and you are in debug mode you will see the exception being thrown as a popup dialog. Same as using the test running in debug mode. Running in release mode does not show the exception.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.