質問

I'm working through Pro ASP.NET MVC 4 by Apress and am trying to understand the syntax used in unit testing a particular controller method.

Given a controller method for a class SomeController:

public ViewResult List(int someInt) {

  ViewModel model = new ViewModel {
    ModelObject = new ModelObject {
      ObjectProperty = someInt;
    }
  }

  return View(model);
}

the unit test looks something like this:

[test method]
Some_Test () {

   //...some code here to set up a mock object named 'mock'

   SomeController target = new SomeController(mock.Object);

   //This next line is where the syntax is confusing me
   int result = ((ViewModel)target.List(1).Model).ModelObject.ObjectProperty;

   Assert.AreEqual(result, 1);
}

It's almost like the ViewResult.Model is having to be sort of 'cast' as type ViewModel or something. I'm sure there's a name for this syntax/technique and I'd like to learn more about what's going on here.

Is this technique required because something like:

 int result = target.List(1).Model.ModelObject.ObjectProperty;

doesn't work to be able to access the properties of the model object passed to the view?

役に立ちましたか?

解決

It's just a simple cast embedded into the method chain. target.List(int) returns a ViewResult. ViewResult.Model is typed as an Object so that any model type can be used. Casting it to your ViewModel type in your test is necessary to tell the compiiler what type Model is. It's the equivalent of:

ViewModel model = (ViewModel)target.List(1).Model;
int result = model.ModelObject.ObjectProperty;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top