Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Moq setting up all methods of a mock equally

Let's assume I have the interface

public interface A {
  int Foo1();

  int Foo2();

  int Foo3();
}

and a testing method with a mock (using Moq) like

Mock<A> mock = new Mock<A>();

Now there are basically two testing scenarios:

Scenario 1

I want to test what my system-under-test does if the interface implementation throws a specific exception on any method. So I want to setup all methods to throw the same exception like

mock.Setup(x => x.Foo1()).Throws(new Exception());
mock.Setup(x => x.Foo2()).Throws(new Exception());
mock.Setup(x => x.Foo3()).Throws(new Exception());

Scenario 2

I want to test what my system-under-test does if the methods return any number. So I could think of setup the mock like

mock.Setup(x => x.Foo1()).Returns(1);
mock.Setup(x => x.Foo2()).Returns(1);
mock.Setup(x => x.Foo3()).Returns(1);

Reason: I have many different unit tests for the system-under-test. Some of them are tests for business logic where it makes a difference e.g. what values are returned. But some are just small tests for general behavior, e.g. if the system-under-test throws an exception if one of the used components throws one. Or the opposite, that the system-under-test throws no exception if all components behave as expected. And for these small tests I'm using code like above right now.

Question: Is there a smarter way to initialize all (matching) methods of a Mock the same way? Something like

mock.SetupAll().Throws(new Exception());

or

mock.SetupAll<int>().Returns(1);

(which means: setup those methods which have a return type of int)?

like image 522
Desty Avatar asked Oct 08 '13 17:10

Desty


People also ask

How does Moq mock work?

Mock objects allow you to mimic the behavior of classes and interfaces, letting the code in the test interact with them as if they were real. This isolates the code you're testing, ensuring that it works on its own and that no other code will make the tests fail.

What can be mocked with Moq?

You can use Moq to create mock objects that simulate or mimic a real object. Moq can be used to mock both classes and interfaces.

What is callback in Moq?

Callbacks. A powerful capability of Moq is to attach custom code to configured methods and properties' getters and setters. This capability is often referred to as Callbacks.

Is Moq a testing framework?

The Moq framework is an open source unit testing framework that works very well with . NET code and Phil shows us how to use it.


1 Answers

This can be achieved with SetReturnsDefault, like:

mock.SetReturnsDefault(1);

See SetReturnsDefault in the source for more info: Moq on github

like image 176
Ole Lynge Avatar answered Oct 21 '22 20:10

Ole Lynge