簡體   English   中英

如何在MVC中的動作的單元測試中模擬類

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

我正在現有軟件上實施單元測試。 這些軟件在ASP.NET MVC中,並且我想測試Controller的Action的返回。

但是在這個動作中我有代碼:

 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);

問題是因為最后一行:“ new CatalogService.CatalogService()”

我在Action的其他部分中使用了此類:

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

因此,我該如何模擬測試?

我已經抽象地考慮了接口並發送了如何使用參數,但是我的NInjectModule中沒有Request到IoC,而在其他代碼中此類卻具有其他參數,所以我認為我無法做到IoC。

我該如何用最小起訂量來模擬呢?

謝謝你的幫助。

我已經考慮和測試了很多,現在我必須為測試做模擬。

首先,我為班級創建了一個“工廠”:

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);
    }
}

然后,我已經在NinjectModule中注冊了此接口,並在Controller的構造函數中進行了設置。 因此,我使用以下代碼調用操作:

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

現在,我可以模擬“ ICatalogClientFactory”和“ ICatalogClient”以在單元測試中使用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM