CapableObjects › Forums › SupportForum › Unit test controller with EcoSpaceStrategyHandler?
Tagged: EcoSpaceStrategyHandler, mocking, MVC, unit test
This topic contains 2 replies, has 2 voices, and was last updated by krilbe 5 years, 1 month ago.
-
AuthorPosts
-
Hi,
Some 5+ years ago, Jonas Högström helped us create an ASP.NET WebForms application, that was later converted to a hybrid WebForms/MVC application. During this process one of us (probably me) created a MasterController class, based, I think, on template code from CapableObjects.
This MasterController has evolved, since then, but I think this code is from the template:
protected OurEcoSpace EcoSpace { get { EnsureEcoSpace(); return ecoSpace; } } private void EnsureEcoSpace() { if (ecoSpace == null) { if (ecoSpaceStrategyHandler == null) ecoSpaceStrategyHandler = new EcoSpaceStrategyHandler( SessionStateMode, typeof(OurEcoSpace), SessionStateKey, UsePool ); ecoSpace = (OurEcoSpace)ecoSpaceStrategyHandler.GetEcoSpace(); RegisterServices(ecoSpace); } }
Now, I’m trying to unit test a controller, that references the property
EcoSpace
, but it throws an exception at the call ofecoSpaceStrategyHandler.GetEcoSpace()
, saying there’s no session, and to useGetSessionFreeEcoSpace()
instead.I use NSubstitute to mock a session:
var context = Substitute.For<ControllerContext>(); var session = Substitute.For<HttpSessionStateBase>(); context.HttpContext.Session.Returns(session); MyController c = new MyController() { ControllerContext = context };
But this doesn’t help. I even tried creating a “real” session state class with a simple Dictionary instead of the mock of HttpSessionStateBase, but that doesn’t help either.
So, what do I need to do, to get
EcoSpaceStrategyHandler
to “find” a session state object?When you create EcoSpaceStrategyHandler you need to say SessionStateMode.Never
Did you do that?
What it controls is when to destroy the ESYes, this is the code:
private void EnsureEcoSpace() { if (ecoSpace == null) { if (ecoSpaceStrategyHandler == null) ecoSpaceStrategyHandler = new EcoSpaceStrategyHandler(EcoSpaceStrategyHandler.SessionStateMode.Never, typeof(DiamondsEcoSpace), null, false); ecoSpace = (DiamondsEcoSpace)ecoSpaceStrategyHandler.GetEcoSpace(); } }
To work around the problem I added a constructor to the controller class that takes an explicit EcoSpace as a parameter, and in that case never instantiates its own, nor an
EcoSpaceStrategyHandler
. Works. -
AuthorPosts
You must be logged in to reply to this topic.