Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moq caches return value

Tags:

moq

Seems like Moq is caching data I set up as return. When I do this:

var service = new Mock<AlbumService>();
service.Setup(x => x.CreateOne()).Returns(new AlbumService().CreateOne());

it returns the same object even thought AlbumService.CreateOne() returns new Album instance.

Is it possible to make Moq call the Returns Action every time I access CreateOne() ?

like image 389
Vladimir Avatar asked Dec 06 '10 14:12

Vladimir


1 Answers

This ought to help:

var service = new Mock<AlbumService>();
service.Setup(x => x.CreateOne()).Returns(() => new AlbumService().CreateOne());

To elaborate, the Returns method accepts an object of the return type or a delegate that will evaluate to the return type. The delegate is invoked whenever the mocked method is invoked.

like image 97
Mark Seemann Avatar answered Sep 23 '22 23:09

Mark Seemann