c#


Moq Mocking and tracking Session values


I'm having problems returning a Session value set from mocking using Moq. Using the following
public class TestHelpers
{
public long sessionValue = -1;
public HttpContextBase FakeHttpContext()
{
var httpContext = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
httpContext.Setup(x => x.Session).Returns(session.Object);
httpContext.SetupGet(x => x.Session["id"]).Returns(sessionValue);
httpContext.SetupSet(x => x.Session["id"] = It.IsAny<long>())
.Callback((string name, object val) =>
{
sessionValue = (long)val;
});
}
}
When I try to obtain the value outside using
var th = new TestHelpers();
HttpContextBase httpContext = th.FakeHttpContext();
do some stuff that sets Session["id"]
var sessionid = httpContext.Session["id"];
sessionid turns out to be -1. But I can obtain the set session value using
th.sessionValue
What's wrong? Can't I simply return the set value via Moq?
I need to stop answering my own questions. It turns out that I needed to mock Session["id"] again like so ...
httpContext.SetupSet(x => x.Session["id"] = It.IsAny<long>())
.Callback((string name, object val) =>
{
sessionValue = (long)val;
httpContext.SetupGet(x => x.Session["id"]).Returns(sessionValue);
});
Moq's Setup methods do not work work with indexed properties that have string indexes. See here: How to MOQ an Indexed property
It's because you're returning the value in the getter which was passed by value. So everytime you invoke the getter, you get the same value returned.
Change the Returns() to use a delegate so it is evaluated every time. That way you will get the correct value every time :)
Much easier on the eye than a SetupGet embedded inside a SetupSet.
httpContext.SetupSet(x => x.Session["id"] = It.IsAny<long>())
.Callback((string name, object val) => sessionValue = (long)val);
httpContext.SetupGet(x => x.Session["id"]).Returns(() => sessionValue);
I just spent long time trying to figure out the easiest way to do it with moq, below is a copy past of my code that actually worked for me :
var _adminctrl = new Moq.Mock<AdminController>(); //AdminController is my MVC controller
var mock = new Mock<ControllerContext>();
mock.Object.Controller = _adminctrl.Object;
mock.Setup(p => p.HttpContext.Session["UserInfoKey"]).Returns(new ViewModel());
//here is the catch, attaching the ControllerContext to your controller
_adminctrl.Object.ControllerContext = mock.Object;
hope this helps!

Related Links

ASP.net C# Return JS Alert from another thread
Asp.net C# Webform forms Generator/Builder [closed]
Lambda event handler scope
Get OS-Version in WinRT Metro App C#
Enumerating DataPoints in view
Switching control backColor fast
How can a view fill a model?
Iterating form controls that are created at runtime
How to use a Resource Image in Word document?
detecting type of generics within generics
Stuck with httpwebrequest usage
ScriptManager Error in my code?
How to reduce the number of TCP ACK's during a highly reliable bulk transfer
Is this good practice for a Custom Exception?
Dynamically generate property getter/setter through reflection or similar
Ascending List Permutation

Categories

HOME
c#
youtube-api
sql-server-2014
ns2
ldap
window.open
file-upload
ibm
gaussian
magento-1.9.2.1
thermal-printer
aggregate-functions
rmarkdown
rtc
velocity
suitecrm
repeater
yui
opendaylight
game-engine
views
project-reactor
connectiq
handle
scrapy-spider
android-6.0-marshmallow
hierarchical-data
proof-general
drombler-fx
pypy
ipython-parallel
undo
postgresql-9.6
mootools
azure-vm-scale-set
device-driver
strategy-pattern
jquery-ui-slider
php-mongodb
web-technologies
firefox-developer-edition
infovis
google-chrome-storage
denodo
visio-2010
perldoc
catalyst
sharing
stringbuilder
fileopendialog
computed-properties
strtol
virtualenvwrapper
git-cherry-pick
qtruby
cherry-pick
db2-zos
window.location
std
sqldataadapter
nonblocking
libgcrypt
edgar
notice
roslyn-code-analysis
p4python
tinymce-plugins
perfect-scrollbar
register-allocation
breeze-sharp
windows-search
oxygenxml
serializer
scjp
winrun4j
dayofweek
facebook-java-api
mysql-error-1146
maven-javadoc-plugin
typography
auctex
idoc
m3u
motordriver
databus
yii-cactiverecord
automapper-2
umfpack
html5-animation
conditional-operator
virtual-destructor
datarelation
google-local-search
oaw
managed-code

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App