0

I would like to test my Web api in asp.net core 2.0 using moq. With operations like : GetAll, getByID there is no problem. But issue starts when I want to test methods like Insert or Update. Whenever I configure setup for example :

serviceMock.Setup(x => x.Update(someModel))
                    .Returns(someModel);

then call method for Controller under test :

ControllerUnderTest.UpdateRespondentList(someModel.ID, someModel);

Controller receives data properly but counter for my mock list doesn't increase.

I would like you to ask that is there other way then testing this using .Verify() method or create completely new List ?

-- there is what I mean : Unit testing LINQ to SQL CRUD operations using Moq

There is how I inject mocked service :

ControllerUnderTest = new RespondentListController(_config, serviceMock.Object);

In my opinion cinfiguration works because whenever I test methods like : getall I have an access to mockedSerivice

Algorithm should looks like this : Insert object into mocked list via ControllerUnderTest -> Asser.Equal (prevStateOfCounter, currentStateOfCounter-1)

Kenik
  • 103
  • 1
  • 15

1 Answers1

1

You should be able to to verify the number of times the method is called similar to below;

serviceMock.Verify(m=>m.Update(someModel),Times.Once);

or

serviceMock.Verify(m=>m.Update(someModel),Times.Exactly(x);

Alternatively, you could implement a callback that you can Assert against;

int methodCount= 0;
serviceMock.Setup(m => m.Update(someModel)).Callback(() => methodCount++ ).Returns(someModel);
ChrisBint
  • 12,773
  • 6
  • 40
  • 62
  • Yes I already know that ;) But what I ask is there other way to test this like increase count counter in my service list of mocked object other than in posted link by me – Kenik Aug 20 '18 at 08:48
  • 1
    Your example update method will not increase any count in the underlying List, so you can only count how many times the method was called. You can do this as per above, or you could implement a callback in your mock that does increment a counter that you can then Assert against. – ChrisBint Aug 20 '18 at 09:08
  • But I still want to add an element to the list which should cause counter increment. – Kenik Aug 20 '18 at 10:01
  • @Kenik you can add it to the fake list in the callback before returning – Nkosi Aug 20 '18 at 10:09
  • OK, I thought there may be other way than that ;) Thank you for your response ;) – Kenik Aug 20 '18 at 10:31