我想使用moq在asp core 2.0中测试我的Web api.使用诸如:GetAll,getByID之类的操作没有问题.但是,当我要测试插入"或更新"之类的方法时,问题就开始了.每当我配置设置时,例如:
I would like to test my Web api in asp 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.
我想问问,还有什么其他方法可以使用.Verify()方法进行测试或创建全新的List吗?
I would like you to ask that is there other way then testing this using .Verify() method or create completely new List ?
-我的意思是:使用Moq对LINQ to SQL CRUD操作进行单元测试
这是我注入模拟服务的方式:
There is how I inject mocked service :
ControllerUnderTest = new RespondentListController(_config, serviceMock.Object);我认为cinfiguration之所以有效,是因为每当我测试诸如getall之类的方法时,我都可以访问mockedSerivice
In my opinion cinfiguration works because whenever I test methods like : getall I have an access to mockedSerivice
算法应如下所示:通过ControllerUnderTest-> Asser.Equal(prevStateOfCounter,currentStateOfCounter-1)将对象插入到模拟列表中
Algorithm should looks like this : Insert object into mocked list via ControllerUnderTest -> Asser.Equal (prevStateOfCounter, currentStateOfCounter-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);或
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);更多推荐
使用Moq测试API CRUD操作
发布评论