Rhino mocks of properties property - c#

When I do these two lines after each other my code fails with Previous method 'HttpContextBase.get_Request();' requires a return value or an exception to throw. on the second line.
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
However when I do just one of the rows the code runs fine.
Doing the following does not fix the problem.
context.Expect(c => c.Request).Return(request);
Anyone understands this strange behaviour?
Thanks,
Drutten
Edit: Entire code is:
public static class Extensions
{
public static HttpContextBase FakeHttpContext()
{
var context = MockRepository.GenerateMock<HttpContextBase>();
var request = MockRepository.GenerateMock<HttpRequestBase>();
var response = MockRepository.GenerateMock<HttpResponseBase>();
var session = MockRepository.GenerateMock<HttpSessionStateBase>();
var server = MockRepository.GenerateMock<HttpServerUtilityBase>();
var writer = new StringWriter();
var form = new NameValueCollection();
request.Expect(r => r.Form).Return(form);
var uri = new Uri("http://localhost/IntegrationTests");
request.Expect(r => r.UrlReferrer).Return(uri).Repeat.Any();
var queryString = new NameValueCollection();
request.Expect(r => r.QueryString).Return(queryString);
context.Expect(c => c.Request).Return(request).Repeat.Any();
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
context.Expect(c => c.Response).Return(response);
context.Expect(c => c.Session).Return(session);
context.Expect(c => c.Server).Return(server);
context.Expect(c => c.Items).Return(new Dictionary<object, object>());
response.Expect(c => c.Output).Return(writer);
return context;
}
public static void MockControllerContext(this Controller controller)
{
var httpContext = FakeHttpContext();
var routeData = new RouteData();
routeData.Values.Add("controller", "Home");
routeData.Values.Add("action", "Index");
controller.ControllerContext = new ControllerContext(new RequestContext(httpContext, routeData), controller);
}
}

I fixed the problem. The problem was probably related to the mix of
context.Expect(c => c.Request.UrlReferrer).Return(uri).Repeat.Any();
and
context.Expect(c => c.Request).Return(request).Repeat.Any();
Working code is:
var uri = new Uri("http://localhost/IntegrationTests");
request.Expect(r => r.UrlReferrer).Return(uri).Repeat.Any();
var queryString = new NameValueCollection();
request.Expect(r => r.QueryString).Return(queryString);
request.Expect(c => c.HttpMethod).Return("POST").Repeat.Any();
context.Expect(c => c.Request).Return(request).Repeat.Any();
I find it strange though that doing
context.Expect(c => c.Request.HttpMethod).Return("POST").Repeat.Any();
once worked, even when not setting return on Request.

Related

C# Fixture OmitAutoProperties

Is there any way to use OmitAutoProperties except entity.Id (Key) and only User.Id (ForeignKey)?
var user = new Fixture().Build<User>().Create();
var entity = new Fixture().Build<Game>().With(x => x.User, user).Create();
You can use With:
var fixture = new Fixture();
var user = fixture
.Build<User>()
.OmitAutoProperties()
.With(p => p.Id)
.Create();
var entity = fixture
.Build<Game>()
.OmitAutoProperties()
.With(p => p.Id)
.With(p => p.User, user)
.Create();

Access Html string returned by controller method programmatically when testing C#

I am trying to test one of the views. First I authenticate and Login user to get needed Cookies information, then I want to check the look of IndexView from HomeController.
[TestClass]
public class HomeControllerTest
{
[TestMethod]
public void IndexView()
{
// Setup Moq config for controller context
moqContext = new Mock<HttpContextBase>();
moqRequest = new Mock<HttpRequestBase>();
moqResponse = new Mock<HttpResponseBase>();
moqSession = new Mock<HttpSessionStateBase>();
moqServer = new Mock<HttpServerUtilityBase>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);
moqContext.Setup(x => x.Request).Returns(moqRequest.Object);
moqContext.Setup(x => x.Request.Cookies).Returns(new HttpCookieCollection());
moqContext.Setup(x => x.Response).Returns(moqResponse.Object);
moqContext.Setup(x => x.Response.Cookies).Returns(new HttpCookieCollection());
moqContext.Setup(x => x.Session).Returns(moqSession.Object);
moqContext.Setup(x => x.Server).Returns(moqServer.Object);
moqContext.Setup(x => x.User).Returns(principal);
var contextRequest = new HttpRequest("", "http://localhost:port/User/Login", "");
var contextResponse = new HttpResponse(new StringWriter());
HttpContext.Current = new HttpContext(contextRequest, contextResponse);
HttpContext.Current.User = principal;
// Authenticate User
IUserAppService _usuarioApp = _container.GetInstance<IUserAppService>();
var user = _usuarioApp.AutenticateUser("user", "password");
var userController = _container.GetInstance<UserController>();
userController.ControllerContext = new ControllerContext(moqContext.Object, new RouteData(), userController);
var res = userController.RealizaLogin(true, "", user) as RedirectToRouteResult;
foreach (var key in moqContext.Object.Response.Cookies.AllKeys)
{
var cookieItem = moqContext.Object.Response.Cookies[key];
HttpContext.Current.Request.Cookies.Add(cookieItem);
moqContext.Object.Request.Cookies.Add(cookieItem);
}
var homeController = _container.GetInstance<HomeController>();
homeController.ControllerContext = new ControllerContext(moqContext.Object, new RouteData(), userController);
var result = homeController.Index() as ViewResultBase;
//here do not know what to do
}
}
but I don't know how to get this rendered HTML. Is there any way?

Moq C# Callback can we get List/Collection for callback parameter

var callArgs = new List<string>();
mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
.Returns(true)
.Callback((string s) => callArgs.Add(s));
Similarly can we do Callback for List parameter
var callArgs = new List<string>();
mock.Setup(foo => foo.DoSomething(It.IsAny<List<string>>()))
.Returns(true)
.Callback((List<string> s) => callArgs.AddRange(s));
Is this possible somehow if not why?
var ex = new List();
myrMock.Setup(x => x.foo(It.IsAny>(), It.IsAny>(), It.IsAny()))
.Callback((IList sy, IList v,string str) => ex.AddRange(sy));
I am not getting anything in ex list.
Yes, you can, exactly as you described.
Or you can use this format:
var callArgs = new List<string>();
mock.Setup(foo => foo.DoSomething(It.IsAny<List<string>>()))
.Returns(true)
.Callback<List<string>>(s => callArgs.AddRange(s));
https://github.com/Moq/moq4/wiki/Quickstart

Count files from request with Moq

The SetupGet for Form work, but the Count not work. How to resolve to Count return the value expected?
var httpContextMock = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
httpContextMock.SetupGet(x => x.Request).Returns(request.Object);
httpContextMock.SetupGet(x => x.Request.Form).Returns(form);
httpContextMock.SetupGet(x => x.Request.Files.Count).Returns(2);
It is not working because you are setting up the wrong mock. Apply the setup on the request mock.
var httpContextMock = new Mock<HttpContextBase>();
var requestMock = new Mock<HttpRequestBase>();
requestMock.Setup(_ => _.Form).Returns(form);
requestMock.Setup(_ => _.Files.Count).Returns(2);
httpContextMock.Setup(_ => _.Request).Returns(requestMock.Object);
Just to prove the above works, I tested it like this
var context = httpContextMock.Object;
Assert.AreEqual(2, context.Request.Files.Count);
and it worked.
I did a quick test and it works if you access the request through the mock context.
[Test()]
public void Test()
{
var httpContextMock = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
httpContextMock.SetupGet(x => x.Request).Returns(request.Object);
httpContextMock.SetupGet(x => x.Request.Files.Count).Returns(2);
var count = httpContextMock.Object.Request.Files.Count;
Assert.AreEqual(2, count);
}
As Nkosi suggested, however, you probably wanted to setup Files.Count on the requestMock itself.

how to pass both session and Request.URL in unit test c# controller

I have a controller which requires both Session state object and also Url Helper to be mocked from unit test and in this regard i have created the following below code
[TestMethod]
public void PaymentControllerTest_CallPaymentProvider()
{
var controller = new PaymentController();
// var model = new Dictionary<string, string>();
var mockDatabaseWrapper = new MockDatabaseWrapper();
DatabaseWrapper.SetDatabaseWrapper(mockDatabaseWrapper);
var request = new Mock<HttpRequestBase>();
request.SetupGet(x => x.Headers).Returns(
new System.Net.WebHeaderCollection {
{"X-Requested-With", "XMLHttpRequest"} });
request.SetupGet(x => x.Url).Returns(new Uri("http://localhost"));
var context = new Mock<HttpContextBase>();
context.SetupGet(x => x.Request).Returns(request.Object);
controller.ControllerContext = new ControllerContext(context.Object, new System.Web.Routing.RouteData(), controller);
controller.Url = new UrlHelper(new System.Web.Routing.RequestContext(controller.HttpContext, new RouteData()), new RouteCollection());
RouteCollection routes = new System.Web.Routing.RouteCollection();
var mockControllerContext = new Mock<ControllerContext>();
var mockSession = new Mock<HttpSessionStateBase>();
mockSession.SetupGet(Session => Session["CurrentCulture"]).Returns(1); //somevalue
mockControllerContext.Setup(p => p.HttpContext.Session).Returns(mockSession.Object);
var result = controller.CallPaymentProvider(123) as ViewResult;
}
Now the problem is that when i create the controller context i am able to pass only one. can any of the experts help how to pass both session and url in controller context.
Thanks

Categories

Resources