Skip a method execution to unit test controller flow

<>

This question already has an answer here:

Answers


You can't create a new instance of an object and stop the constructor from being called. You would have to create an empty parameterless constructor.

public class ConcreteClass
{
    private string MyString;

    // Your constructor
    public ConcreteClass(string myString)
    {
        this.MyString = myString;
    }

    // Parameterless constructor
    public ConcreteClass()
    {
        // Do nothing, no code
    }

    // A method that might use MyString
    public void DoSomethingWithMyString()
    {
        var trimmedString = this.MyString.Trim();
    }
}

Either that or re-factor the way that your methods work so that it doesn't rely on having a string passed in on the constructor:

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

However, that probably doesn't solve the problem, bearing in mind that you want to inject your Request variable and you don't have access to them, can't you just do the following:

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

Now within your Unit Tests you can use the second constructor and pass the value in:

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

Need Your Help

How to check 32bit or 64bit Internet Explorer 10 and 11?

windows process operating-system internet-explorer-11

Before IE10 (likes IE9), I can use window.navigator.platform to check IE is 32bit or 64bit.

Is there way for a GWT program to tell if it's in hosted or web mode?

java gwt

I would like my GWT program to be able to determine whether it's in hosted mode or in web mode. Is there a way to do this?