跳过方法执行到单元测试控制器流程

时间:2015-11-30 09:54:24

标签: asp.net-mvc unit-testing dependency-injection nunit moq

public class DemoController : Controller
{


    private readonly ICommonOperationsRepository _commonRepo;

    public DemoController (ICommonOperationsRepository commonRepo)
    {
       _commonRepo = commonRepo;
    }
    public ActionResult Default()
    {
       var model = new DemoModel();
       try
       {
           **ConcreteClass cc = new ConcreteClass(Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString());
            cc.ConcreteClassMethod();**

           model.ListTopListing.AddRange(_commonRepo.GetListings());
        }
        catch (Exception ex)
        {
            ExceptionHandler objErr = new ExceptionHandler(ex, "DemoController .Default()\n Exception : " + ex.Message);
            objErr.LogException();
         }
         return View(model);
     }

}

我正在尝试对我的控制器进行单元测试。 ConcreteClass构造函数及其方法ConcreteClassMethod都对HttpRequest变量有一些依赖,我无法从单元测试中传递。

我想要一种方法,当我调用DemoController的默认动作时,我可以简单地跳过ConcreteClass的构造函数和ConcreteClassMethod的执行。

1 个答案:

答案 0 :(得分:0)

您无法创建对象的新实例并停止调用构造函数。您必须创建一个空的无参数构造函数。

public class ConcreteClass
{        
    // No constructor required anymore

    // Pass the string in to the methods that need the string
    public void DoSomethingWithMyString(string myString)
    {
        var trimmedString = myString.Trim();
    }

    // Pass the string in to the methods that need the string
    public void DoSomethingElseWithMyString(string myString)
    {
        var trimmedString = Int32.Parse(myString);
    }
}

或者重新考虑你的方法的工作方式,以便它不依赖于在构造函数中传入一个字符串:

Request

然而,这可能无法解决问题,请记住您想要注入public class DemoController : Controller { private string HttpRewriteUrl; public DemoController() { this.HttpRewriteUrl = Request.ServerVariables["HTTP_X_REWRITE_URL"].ToString(); } // Custom constructor for unit testing public DemoController(string httpRewriteUrl) { this.HttpRewriteUrl = httpRewriteUrl; } public ActionResult Default() { // Get the value from the object ConcreteClass cc = new ConcreteClass(this.HttpRewriteUrl); cc.ConcreteClassMethod(); } } 变量并且您无法访问它们,不能只是你执行以下操作:

var controller = new DemoController("your value to pass in here");
controller.Default();

现在,在单元测试中,您可以使用第二个构造函数并传递值:

import random

def guess(secret,testWord):

    return (len([(x, y) for x, y in zip(secret, testWord) if x==y]))


words = ('\nSCORPION\nFLOGGING\nCROPPERS\nMIGRAINE\nFOOTNOTE\nREFINERY\nVAULTING\nVICARAGE\nPROTRACT\nDESCENTS')
Guesses = 0

print('Welcome to the Word Guessing Game \n\nYou have 4 chances to guess the word \n\nGood Luck!')
print(words)

words = words.split('\n')
WordToGuess = random.choice(words)

GameOn = True
frequencies = []

while GameOn:

currentguess = input('\nPlease Enter Your Word to Guess from the list given').upper()
Guesses += 1
print(Guesses)

correctLength = guess(WordToGuess,currentguess)

if correctLength == len(WordToGuess):
    print('Congragulations, You Won!')
    GameOn = False
else:
    print(correctLength, '/', len(WordToGuess), 'correct') 

if Guesses >= 4:
    GameOn = False
    print('Sorry you have lost the game. \nThe word was ' + WordToGuess)
相关问题