How to Return Null value from method using FakeItEasy - c#-4.0

I have a service faked using FakeitEasy and i am trying to call its method. Here is the Code
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(null);
The method GetUserProfile returns some object in actual implementation. but for some reason i want this method to return null. I am using above code to acomplish this purpose but its returning Fake object instead of null.
Here is the Test Setup i am using
[Test]
public void MyTest(string sitecollectionGuid, string customerName)
{
var mockHttpContext = SetupHttpContext(sitecollectionGuid, customerName);
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(null);
var controllerContext = new ControllerContext(mockHttpContext, new RouteData(), A.Fake<ControllerBase>());
controller.ControllerContext = controllerContext;
var result = controller.CheckUsername(userName);
Assert.IsNotNull(result, "Result is not as expected");
}
Production Method looks like the following
public UserDAO GetUserProfile(string userName)
{
UserDAO objUserProfile = new UserDAO();
IUsers objUsers = (IUsers)Global.Container["Users"];
IUser objUser = objUsers.GetByUserName(userName);
if (objUser == null)
{
return null;
}
else
{
objUserProfile = AutoMapper.Mapper.Map<IUser, UserDAO>(objUser);
objUserProfile.FirstName = objUser.FirstName;
objUserProfile.MiddleName = objUser.MiddleName;
objUserProfile.LastName = objUser.LastName;
....................
....................
<setting other properties>
....................
....................
return objUserProfile;
}
}
Any help will be appreciated
Thanks

Try and type your (null) reference.
UserDAO returnValue = null;
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns(returnValue);

In order to configure a method, it has to be virtual, abstract, or defined on an interface that you're faking. However,
public UserDAO GetUserProfile(string userName)
is neither virtual nor abstract, so unless you're creating a fake from an interface, this will not work. However, A.CallTo will raise an error when trying to configure either a non-virtual method or a method on a concrete (not faked) object, and you've not mentioned either of these things happening.
From your code, we still can't tell
where client came from (I know, the container, but how did it get there?),
whether controller uses the same client, and
what the connection between controller.CheckUsername and client.GetUserProfile is
My guesses at this point are
whatever controller is using to CheckUsername, it's not the same client that the test has, or
client.GetUserProfile is being called with the wrong userName (although you use the same one in controller.CheckUsername(userName), so that seems less likely)
If you're unable or unwilling to connect the dots, I suggest checking the value of userName at all points, and making sure that when client is called in the production code, it's a faked object (debug in and examine the type—it should be clear whether its your type or the faked one).

or you could just cast the null to the type in context.
var client = container.Resolve<MyService>();
A.CallTo(() => client.GetUserProfile(userName)).Returns((UserDAO) returnValue);

Related

Filtering out soft deletes with AutoQuery

I'm using ServiceStack with OrmLite, and having great success with it so far. I'm looking for a way to filter out 'soft deleted' records when using AutoQuery. I've seen this suggestion to use a SqlExpression, but I'm not sure where you would place that. In the AppHost when the application starts? I did that, but the deleted records still return. My QueryDb request object in this case is as follows:
public class QueryableStore : QueryDb<StoreDto>
{
}
Other SqlExpressions I've used are in the repository class itself, but being that I'm using QueryDb and only the message itself (not leveraging my repository class) I don't have any other code in place to handle these messages and filter out the 'deleted' ones.
I've also tried using a custom service base as suggested by this approach as well, using the following:
public abstract class MyCustomServiceBase : AutoQueryServiceBase
{
private const string IsDeleted = "F_isdeleted";
public override object Exec<From>(IQueryDb<From> dto)
{
var q = AutoQuery.CreateQuery(dto, Request);
q.And("{0} = {1}", IsDeleted, 0);
return AutoQuery.Execute(dto, q);
}
public override object Exec<From, Into>(IQueryDb<From, Into> dto)
{
var q = AutoQuery.CreateQuery(dto, Request);
q.And("{0} = {1}", IsDeleted, 0);
return AutoQuery.Execute(dto, q);
}
}
This code gets called, but when the Execute call happens I get an error:
System.ArgumentException: 'Conversion failed when converting the varchar value 'F_isdeleted' to data type int.'
The F_isdeleted column is a 'bit' in SQL Server, and represented as a bool in my POCO.
Any ideas on what would work here? I'm kind of at a loss that this seems this difficult to do, yet the docs make it look pretty simple.
The {0} are placeholders for db parameters, so your SQL should only be using placeholders for DB parameters, e.g:
var q = AutoQuery.CreateQuery(dto, Request);
q.And(IsDeleted + " = {0}", false);
Otherwise if you want to use SQL Server-specific syntax you can use:
q.And(IsDeleted + " = 0");

AsyncCallback with completed event

I am Creating a library using Facebook C# SDK for windows phone.Facebook SDK Library version is 6.0.10.0. Facebook C# SDK contains asynchronous function calls only.
In which there is a postCompleted event handler which takes object and FacebookApiEventArgs as arguments and return type is void.
I am using two classes one is UI class and other is Businesslogic class. from UI i want to call the BusinessLogic class(s) PostWall function which will simply return the last message id.
I want to create a function something like this
public string PostWall(string accessToken, string message)
{
var fb = new FacebookClient(accessToken);
fb.PostCompleted += (o, args) =>
{
if (args.Error != null)
{
return;
}
var result = (IDictionary<string, object>)args.GetResultData();
_lastMessageId = (string)result["id"];
};
var parameters = new Dictionary<string, object>();
parameters["message"] = message;
fb.PostAsync("me/feed", parameters);
}
I do not know how to implement this. Is this functionality achievable or not.
Any help appreciated
Thanks in Advance
you can check out the wp7 sample at at https://github.com/facebook-csharp-sdk/facebook-windows-phone-sample.
What you are doing is already correct.

Populating IAuthSession with data from the database

So I've created a custom CredentialsAuthProvider using ServiceStack as per the examples located here:
https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization
I have the authentication side of things working but I'm not sure how I populate the session with data from the database in the OnAuthenticated method. In the example they show the following:
//Fill the IAuthSession with data which you want to retrieve in the app eg:
session.FirstName = "some_firstname_from_db";
In the TryAuthenticate method I have the username/password, which I can use to authenticate the user against the database, but once it goes to the OnAuthenticated method, how/what do I use to access/retrieve the user information from the database?
I know this is an older thread but it may still be relevant because unfortunately not much has improved since Sep of 2012 in terms of availability of ServiceStack documentation, clarity of examples or even comments in the code. (#mythz: It would be very helpful if you guys could add meaningful summaries to all your classes and methods.)
I struggled with the same dilemma until I looked at the actual code of CredentialsAuthProvider (which in general is pretty much the only way to understand how things work in ServiceStack). The OnAuthenticated is called right after TryAuthenticate inside the Authenticate method, so I figured it's not necessary to make all your DB calls in OnAuthenticated as #mythz suggests in his examples. Instead I placed the code that populates the IAuthSession object right into my implementation of TryAuthenticate, like so:
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
try
{
// Use my own repo to authenticate the user.
var userRepo = authService.TryResolve<IUserRepository>();
var user = userRepo.Authenticate(userName, password);
// Populate session properties with data from my user POCO.
var session = authService.GetSession();
session.Id = user.CurrentSession.ID.ToString();
session.IsAuthenticated = true;
session.CreatedAt = DateTime.UtcNow;
session.DisplayName = session.FirstName = session.LastName = user.FullName;
session.UserAuthName = session.UserName = user.Username;
session.UserAuthId = user.ID.ToString();
}
catch (Exception ex)
{
// Log the exception, etc....
return false;
}
return true;
}
However, you still have to override OnAuthenticated in order to save the cookie in HTTP response (which I assume is required for subsequent requests from the same browser to be authenticated) because the base implementation only sets the cookie if it finds IUserAuthRepository in the IOC container, which in my case won't happen because I use my own repository. So my implementation now looks like this:
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
try
{
// Save the browser cookie.
var httpRes = authService.RequestContext.Get<IHttpResponse>();
if (httpRes != null)
{
httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
}
// Save the user session object (ServiceStack stores it in the in-memory cache).
authService.SaveSession(session, SessionExpiry);
}
catch (Exception ex)
{
// Log the exception, etc....
}
}
#mythz: Please let me know if the above makes sense or not.
Another good example of a ServiceStack's CustomUserSession is in the SocialBootstrapApi project. Rather than pulling information out of the data, it extracts the information out of the UserSession and populates its own Custom User Table using the registered DB Factory resolved from the AppHost IOC:
authService.TryResolve<IDbConnectionFactory>().Run(db => db.Save(user));
Rather than using it to extract and save data from the user's session, you can also use any of your registered dependencies to fetch data and populate the session with:
public override void OnAuthenticated(
IServiceBase authService,
IAuthSession session,
IOAuthTokens tokens,
Dictionary<string, string> authInfo)
{
using (var db = authService.TryResolve<IDbConnectionFactory>().OpenDbConnection())
{
var user = db.Id<MyUser>(session.UserId);
session.FirstName = user.FirstName;
}
}

first steps with FakeItEasy and problems with Action type

I have the following (here simplified) code which I want to test with FakeItEasy.
public class ActionExecutor : IActionExecutor
{
public void TransactionalExecutionOf(Action action)
{
try
{
// ...
action();
// ...
}
catch
{
// ...
Rollback();
}
}
public void Commit()
{ }
public void Rollback()
{ }
}
public class Service : IService
{
private readonly IRepository _repository;
private readonly IActionExecutor _actionExecutor;
// ctor for CI
public void ServiceMethod(string name)
{
_actionExecutor.TransactionalExecutionOf(() =>
{
var item = _repository.FindByName(ItemSpecs.FindByNameSpec(name));
if (item == null) throw new ServiceException("Item not found");
item.DoSomething();
_actionExecutor.Commit();
}
}
}
I want to test that the ServiceException is thrown so i setup my test like that
var repo = A.Fake<IRepository>();
A.CallTo(() => repo.FindByName(A<ISpec<Item>>.Ignored))
.Returns(null);
var executor = A.Fake<IActionExecutor>();
executor.Configure()
.CallsTo(x => x.Rollback()).DoesNothing();
executor.Configure()
.CallsTo(x => x.Commit()).DoesNothing();
executor.Configure()
.CallsTo(x => x.TransactionalExecutionOf(A<Action>.Ignored))
.CallsBaseMethod();
With the following code
var service = new Service(executor, repo);
service.ServiceMethod("notExists")
.Throws(new ServiceException());
I get the following message
The current proxy generator can not intercept the specified method
for the following reason:
- Sealed methods can not be intercepted.
If I call the method directly on the service like
var service = new Service(executor, repo);
service.ServiceMethod("NotExists");
I get this message
This is a DynamicProxy2 error: The interceptor attempted to 'Proceed'
for method 'Void TransactionalExecutionOf(System.Action)' which has no
target. When calling method without target there is no implementation
to 'proceed' to and it is the responsibility of the interceptor to
mimic the implementation (set return value, out arguments etc)
Now I am a bit confused and don't know what to do next.
Problems comes from the way you create fake and what you later expect it to do:
var executor = A.Fake<IActionExecutor>();
// ...
executor.Configure()
.CallsTo(x => x.TransactionalExecutionOf(A<Action>.Ignored))
.CallsBaseMethod();
What base method? FakeItEasy has no idea what the base class is, and hence the DynamicProxy2 exception in your second case. You can create partial mock this way:
var executor = A.Fake<ActionExecutor>();
Note that we're basing on actual implementation, not interface anymore
This however introduces a new set of problems, as methods on ActionExecutor are not virtual and therefore interceptor cannot hook up to well - intercept them. To make your current setup work, you'll have to change your ActionExecutor and make (all) the methods virtual.
However, you may (or even should) want to avoid modifications of existing code (which sometimes might not even be an option). You could then set up your IActionExecutor fake like this:
var executor = A.Fake<IActionExecutor>();
A.CallTo(() => executor.TransactionalExecutionOf(A<Action>.Ignored))
.Invokes(f => new ActionExecutor()
.TransactionalExecutionOf((Action)f.Arguments.First())
);
This will allow you to work on faked object, with the exception of call to TransactionalExecutionOf which will be redirected to actual implementation.

Storing a reference to an object to be

I don't know if this is possible at all so this is a shot in the dark.
Anyhow...
Consider having the following model:
Class Model
{
public List<string> TheList = null;
}
The List is set to null on purpose.
var model = new Model();
command.RegisterInData( model => model.TheList ); // TheList is null at this point
model.TheList = new List<string>();
model.TheList.Add("A value here");
command.Execute(); // <-- Here I want to access the new list somehow
As said, I don't know if anything like this is possible but I would like a push in the right direction.
The function desired: I would like to tell the command where to put the result before I have a concrete object.
Thanks in advance
This seems quite doable. Here is a variation with an even simpler accessor:
class Command
{
private Func<List<string>> listAccessor;
public void RegisterInData(Func<List<string>> listAccessor)
{
this.listAccessor = listAccessor;
}
public void Execute()
{
var list = this.listAccessor();
foreach (string s in list)
{
Console.Log(s);
}
}
}
// Elsewhere
var model = new Model();
command.RegisterInData(() => model.TheList);
model.TheList = new List<string>();
model.TheList.Add("A value here");
command.Execute();
You'll probably want error handling for the case where RegisterInData is not called before Execute, but you get the idea.
You simply have to delay calling the delegate passed to RegisterInData and call it (I guess) at Execute.
Could Lazy be of use here? http://msdn.microsoft.com/en-us/library/dd642331.aspx

Resources