mosquito87
mosquito87

Reputation: 4440

Mocking an insert method of a repository

I would like to unit test the following method:

void Insert(TEntity entity);

The class of this method is already mocked (I'm using Moq).

Now I'd like to do a state based test and tell Moq if this method is called, an object has to be inserted to a list. How can I do that?

useraccountRepository.Setup(r => r.Insert(useraccountBeforeLogin)).???

What comes here? There's a raises method which would raise an event. Can I use this?

Upvotes: 5

Views: 4959

Answers (2)

RobJohnson
RobJohnson

Reputation: 885

I know this is an old thread, but this is what I did to test that items are inserted from a mocked repository, hopefully this might help someone.

var myRepositoryMock = new Mock<IMyRepository>();

var itemsInserted = new List<MyItem>();

myRepositoryMock 
    .Setup(i => i.InsertItem(It.IsAny<MyItem>()))
    .Callback((MyItem item) => itemsInserted.Add(item));

Upvotes: 11

AdaTheDev
AdaTheDev

Reputation: 147224

You can use callbacks - there's a few examples listed there

Upvotes: 3

Related Questions