Mvc: Unit Testing Page Model Throws Null Ref On ModelState check

Created on 12 Oct 2017  路  9Comments  路  Source: aspnet/Mvc

While testing Razor Pages, when I create a new PageModel, it throws a null reference exception when doing the ModelState.IsValid check. The NRE is on ModelState itself.

This seems to be a change from the way MVC's ModelState "just worked" when newing up the controller.

For instance (some Arrange code removed for brevity)...

In MVC:

var controller = new AccountController(dependency1, dependency2);
var result = await controller.Login(new LoginViewModel()));
// **Does NOT** throw NRE on ModelState.IsValid check

In Razor Pages:

var loginModel = new LoginModel(dependency1, dependency2);
var result = await loginModel.OnPostAsync();
// **DOES** throw NRE on ModelState.IsValid check, because ModelState is null.

This is bit of an annoyance.

/cc @DamianEdwards

3 - Done bug

All 9 comments

You should be able to work around this for now by instantiating a PageContext and setting it.

We should fix this, all of this stuff needs to 'just work'. It looks like there are a few more properties that delegate to PageModel, but they need to work well in unit test scenarios like Controller does.

Appreciate the quick response! Was just digging around into how to fix this, so that works! Thanks!

Any plans on this being on the roadmap for say 2.1?

IUrlHelper also throws a null ref

This would be good as part of our efforts to make testing great.

@javiercn I think this need to be closed

@hishamco Nope. There's a PR out for fixing it but its not merged.

@hishamco - that's just to the branch. PR open here - https://github.com/aspnet/Mvc/pull/6953

I see, it's my bad .. sorry

Was this page helpful?
0 / 5 - 0 ratings