Using Moq, setting all layout methods equally

Suppose I have an interface

public interface A { int Foo1(); int Foo2(); int Foo3(); } 

and a test method with a layout (using Moq ), e.g.

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

There are currently two test scenarios:

Scenario 1

I want to check what my system test does if an interface implementation throws a specific exception for any method. So I want 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 check what my system test does if methods return any number. So I could think of setting up a layout 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 test. Some of them are tests for business logic, where it matters, for example. what values ​​are returned. But some of them are just small tests for general behavior, for example. if the system test throws an exception, if one of the components used throws it. Or vice versa, that a system test does not rule out an exception if all components behave as expected. And for these small tests, I'm using the code as above right now.

Question: Is there a smarter way to initialize all (relevant) Mock methods in the same way? Sort of

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

or

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

(which means: configure those methods that have an int return type)?

+6
source share
1 answer

This can be achieved using SetReturnsDefault , for example:

 mock.SetReturnsDefault(1); 

See SetReturnsDefault in the source: Moq on github for details.

+5
source

Source: https://habr.com/ru/post/955514/


All Articles