3

I have a little problem with UnitTests for asp.net mvc3 application.

If I run some unit-tests in Visual Studio 2010 Professional, they have been passed successfully.

If I use the Visual Studio 2010 Professional command line

mstest /testcontainer:MyDLL.dll /detail:errormessage /resultsfile:"D:\A Folder\res.trx"

Then the error occurred:

[errormessage] = Test method MyDLL.AController.IndexTest threw exception:
System.NullReferenceException: Object reference not set to an instance of an object.

and my controller:

public ActionResult Index(){
   RedirectToAction("AnotherView");
}

and in the test

AController myController = new AController();
var result = (RedirectToRouteResult)myController.Index();

Assert.AreEqual("AnotherView", result.RouteValues["action"]);

How to solve this to work properly in both situations (VS2010 and mstest.exe) ?

Thank you

PS: I read Test run errors with MSTest in VS2010 but that could solve if I have VS2010 Ultimate/Premium.

Community
  • 1
  • 1
Snake Eyes
  • 16,287
  • 34
  • 113
  • 221

1 Answers1

1

I found the problem. The problem was AnotherView action.

The action AnotherView contains

private AModel _aModel;

public ActionResult AnotherView(){
  // call here the function which connect to a model and this connect to a DB

  _aModel.GetList();
  return View("AnotherView", _aModel);
}

What is need to works:

1.Make a controller constructor with a parameter like

public AController(AModel model){
  _aModel = model;
}

2.In test or unit-test class, create a mock like

public class MockClass: AModel
{

  public bool GetList(){  //overload this method
     return true;
  }

  // put another function(s) which use(s) another connection to DB
}

3.In current test method IndexTest

[TestMethod]
public void IndexTest(){
   AController myController = new AController(new MockClass());
   var result = (RedirectToRouteResult)myController.Index();

   Assert.AreEqual("AnotherView", result.RouteValues["action"]);
}

Now the unit test will works. Not applicable to Integration tests. There you must provide configuration for a connection to DB and do not apply a mock, just use the code from my question.

Hope this help after researching for 5-6 hours :)

Snake Eyes
  • 16,287
  • 34
  • 113
  • 221