模拟在控制器中使用的方法 [英] Mock a method that is used within a controller

查看:98
本文介绍了模拟在控制器中使用的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在控制器中有以下方法。



I have got the following method in the controller.

public async Task





其中 CientId 在同一个控制器中使用以下方法





Where CientId uses the following method in the same controller

public Guid CientId
       {
           get
           {
               Guid clientIdParam;
               Guid.TryParse(Request.QueryString["clientId"], out clientIdParam);

               return clientIdParam;
           }
           set{ }
       }





现在我正在尝试为上面的控制器方法编写单元,我想在其中模拟行 model.ClientId = CientId



直到现在我已经尝试过以下测试





Now I am trying to write the unit for the above controller method in which I want to mock the line model.ClientId = CientId

Till now I have tried the following test

[Test]
       public async void Edit_edits_booking_form_settings()
       {
           //Arrange
           BookingFormSettingsController controller = Substitute.ForPartsOf





任何人都可以帮我修理我提到的那条线。



我尝试了什么:



我尝试使用部分替代品,automockcontroller



Can anyone please help me moch the line I mentioned .

What I have tried:

I tried using the partial substitute , automockcontroller

推荐答案

我这里真的不够用,但有一个问题就是你在Request.QueryString上创建了一个依赖项。由于这是MVC,为什么不将它添加为模型的一部分呢?



另外,关于这个的另一个注意事项是你看到的ClientId的代码片段就在里面你的控制器。如果是这样,那么你违反了MVC模式规则并且应该将其移到你的模型中。



但是,请看下面的链接。你可能不得不改变你的单元测试方法,以模拟你想要的东西,但这至少应该有所帮助。



如何模拟请求查询字符串 - Google搜索 [ ^ ]



c# - 如何设置查询字符串的值在测试方法Moq - Stack Overflow [ ^ ]
There isn't enough here to go one really, but one issue is that you are creating a dependency on Request.QueryString. Since this is MVC, why not add this as part of your model?

Also, another note about that is it looks like the code snippet of ClientId you mentioned is inside your controller. If that is so, you are breaking MVC pattern rules and should move that to your Model.

However, take a look at the following links. You might have to alter your approach to unit testing some in order to mock what you want but this should help at least.

how to mock request querystring - Google Search[^]

c# - How to set the value of a query string in test method Moq - Stack Overflow[^]


这篇关于模拟在控制器中使用的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆