简体   繁体   English

如何在MVC中的动作的单元测试中模拟类

[英]How mock class in Unit Test for a Action in MVC

I'm implementing Unit Test on existing software. 我正在现有软件上实施单元测试。 These software is in ASP.NET MVC, and I want test the return of a Action, of a Controller. 这些软件在ASP.NET MVC中,并且我想测试Controller的Action的返回。

But in this Action a I have the code: 但是在这个动作中我有代码:

 public ActionResult EditProfile(
        string accountId = null,
        string partnership = null,
        AccountType? subscriptionType = null,
        bool forcePartnerUpdate = false)
    {
        var model = new EditProfileModel();
        var account = _authUser.Account;  
        var catalogClient = new CatalogService.CatalogClient(Request.Cookies, Globals.CatalogURL);

The problem is because the last line : "new CatalogService.CatalogService()" 问题是因为最后一行:“ new CatalogService.CatalogService()”

I'm using this class in other part of Action: 我在Action的其他部分中使用了此类:

model.ListBrands = new List<Brands>();
model.ListAvailableBrands = new List<Brands>();
model.ListSubscribedBrands = new List<Brands>();
var brands = catalogClient.GetBrandsWithManufacturer();

So, How I can mock this for tests? 因此,我该如何模拟测试?

I have thought in abstract for a interface and send how a parameter in action, but I don't have the Request in my NInjectModule to IoC and in other codes this class has other parameters, so I think I can't do IoC. 我已经抽象地考虑了接口并发送了如何使用参数,但是我的NInjectModule中没有Request到IoC,而在其他代码中此类却具有其他参数,所以我认为我无法做到IoC。

How I can mock this with moq? 我该如何用最小起订量来模拟呢?

Thank you for help. 谢谢你的帮助。

I've thought and tested a lot and now I got to do the mock for my tests. 我已经考虑和测试了很多,现在我必须为测试做模拟。

First, I've created a "Factory" to my class: 首先,我为班级创建了一个“工厂”:

public interface ICatalogClientFactory
{
    ICatalogClient Create(HttpCookieCollection cookies, string catalogUrl);
}

public class CatalogClientFactory : ICatalogClientFactory
{
    public ICatalogClient Create(HttpCookieCollection cookies, string catalogUrl)
    {
        return new CatalogClient(cookies, catalogUrl);
    }
}

Than, this Interface I've registered in the NinjectModule and set this in the constructor of Controller. 然后,我已经在NinjectModule中注册了此接口,并在Controller的构造函数中进行了设置。 So, I'm calling in my actions with this code: 因此,我使用以下代码调用操作:

  ICatalogClientFactory _catalogClientFactory = catalogClientFactory;
  var clientCatalog = _catalogClientFactory.Create(Request.Cookies, Globals.CatalogURL);

Now, I can mock "ICatalogClientFactory" and "ICatalogClient" to use in unit tests. 现在,我可以模拟“ ICatalogClientFactory”和“ ICatalogClient”以在单元测试中使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM