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

Fill only last 6 month data from current month in second list from first list in linq
Save an image to a specified path with default filename without SaveFileDialog in C#? [duplicate]
Limited performance with use of permutation and recursion
C# Display SQL data to HTML Textbox based on Textbox ID
using ffmpeg in Azure function to cut files using c#
Adding columns to AspNetUserClaims in ASP.NET Identity
DocumentComplete Event - Add function fails
C# Discord.Net bot deleting messages no responde
Use the for attribute of a label to reference a control inside a repeater
ASP.NET passing List back to controller from IEnumerable #model inside Table header ActionLink with non-indexing
Moq a concrete class method call
Serial Port Coin Acceptor programming c#
Error while sending web push notification using fiddler
ASP.NET c# searching data between two date using the calendar control and report viewer
Creating a static array with already existing objects in C# [duplicate]
C# Object reference not set to an instance of an object. [duplicate]

Categories

HOME
indexing
network-programming
gsm
pyspark
android-ndk
boxplot
data-modeling
google-docs-api
sugarcrm
autocad
sahi
angularjs-ng-repeat
mbed
minimum
greensock
brightway
alert
gomobile
xna
fibonacci
hololens
javaagents
aws-iot
jira-zephyr
datanucleus
android-cursorloader
marionette
cqlsh
sphinx4
ocl
concrete5
drawrect
spring-oauth2
jsonapi-resources
traitsui
azure-vm-scale-set
ragel
leaderboard
respect-validation
motion
byobu
ngrok
observer-pattern
java-5
compiler-warnings
gridgain
spring-ide
line-endings
activeandroid
react.rb
webmatrix
androiddesignsupport
liferay-ide
mongodb-3.3
android-xmlpullparser
python-rq
treelist
calc
clear
updating
firebase-tools
google-experiments
mathics
cordova-3
sync
breeze-sharp
ant-contrib
sigma-grid-control
farpoint-spread
image-preloader
power-management
kernel-density
randomaccessfile
myrrix
inflate
systrace
bash4
towerjs
wdm
file-processing
response-time
s60
dongle
script-tag
authkit
file-icons
qlibrary
disk-based

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