使用Moq测试API CRUD操作

编程入门 行业动态 更新时间:2024-10-24 06:37:57
本文介绍了使用Moq测试API CRUD操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想使用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操作

本文发布于:2023-10-29 08:16:39,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1539186.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:操作   测试   Moq   CRUD   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!