Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq a void method

I'm trying to work out how this Mock (using the Moq framework) stuff all works, but I've become a bit confused with methods that return void.

The original object has the following methods/properties:

void Add(Person entity);
void Save();
IQueryable<Person> Persons;

The Add method calls InsertOnSubmit (it's Linq to sql), and the Save method calls Context.SubmitChanges(). The Person's property returns the Table<News> object.

I'm not sure how I go about mocking these methods however, as I obviously can't use Returns().

Or does my design mean that I can't actually Mock the objects properly?

like image 305
AndrewC Avatar asked Feb 03 '11 16:02

AndrewC


1 Answers

It depends on what you intend to test.

Moq can help you significantly when you want to test interactions between the class being tested and other classes.

In the case you are describing you are presumably testing a class which is using class with methods and properties mentioned above. To verify interactions you want to check if the Add method is called with expected parameters, that the Save method is called and that the Persons property is refered to in order to read results. This can be achieved in the following way:

var mockedClass = new Mock<IDaoClass>();
var classUnderTest = ...

mockedClass.SetupGet(m => m.Persons).Returns(new List<Person>().AsQueryable());

classUnderTest.DoSomething();

mockedClass.Verify( m => m.Add(It.IsAny<Person>())); 
mockedClass.Verify( m => m.Save());

If you want to test something else and provide a stub implementation of these methods then you may want to just create a test implementation or consider using Moq setups with functions expressed as lambdas rather than simple setups.

like image 108
mfloryan Avatar answered Sep 19 '22 12:09

mfloryan