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

Is it possible to bind to a ValueTuple field in WPF with C#7
How to use Acrylic Accent (CreateHostBackDropBrush()) in Windows 10 Creators Update correctly?
Update ProgressBar from Program Class not working
Get by Reflection Properties from a Class
MSBuild log file location
Function not working in Form Load, but works everywhere else
C# Interaction.inputbox 2 inputs
c# DataGridView update cell value
XDocument descendants is throwing a null reference
String combination does not work [closed]
Calculator in C# input from keyboard using “&” in text property
Difficulty starting computing project
asp.net mvc c# listing categories recursively
GroupPrincipal.GetMembers vs LDAP search to get all users from Ad Group including sub group
C# Regular Expression throws Unterminated [] set
WPF ToggleButton Binding Not Working

Categories

HOME
classification
service
wifi
casting
opencv4android
ebay-api
hex
pandoc
ubuntu-14.04
hiveql
download
mediarecorder
aggregation-framework
atlassian-fisheye
angular-universal
mamp
urllib2
mongodb-replica-set
opendaylight
multibinding
views
ampscript
descriptor
cherrypy
pumping-lemma
struts
expressionengine
smart-device
tftp
jsonapi-resources
offset
odp.net
certbot
ansible-inventory
observer-pattern
collation
aspnetboilerplate
flume-ng
uitextview
result
history
cloudconvert
runtime-permissions
enet
sharpssh
ajv
nservicebus6
was
cardview
group
glade
mac-app-store
rowname
tinybox2
particle-system
airwatch
mrunit
libgcrypt
php-gd
self-join
dnvm
log4cxx
pagecontrol
vspackage
tidesdk
copy-on-write
skview
sony-xperia
information-hiding
system.io.packaging
drawable
smartxls
webshim
svg-android
static-class
blotter
vline
linqdatasource
yii-components
cryptarithmetic-puzzle
tasklist
mail-gem
aspmenu-control
win-prolog
commonsware
towerjs
datejs
clgeocoder
rjs
execjs
virtual-destructor
simultaneous
qprocess
manuals
weak-typing
tracd

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