Mock static method with out arguments

4,135 views
Skip to first unread message

Karol Pawłowski

unread,
Jul 17, 2014, 10:58:54 AM7/17/14
to nsubs...@googlegroups.com
Hi Team,

I would like to mock static method in static class where method expects output parameters .... I know it sounds like a fairy tale :)

The method signature looks:
 public static void GetLoggedInUserNameAndId(out int? userID, out string userName, out string userFullName, out string culture)
{
     // do some stuff here
}

and it's called 

int? userId = null;
string userName = String.Empty;
string userFullName = String.Empty;
string culture = "en";

AcceptanceFlow.GetLoggedInUserNameAndId(out userId, out userName, out userFullName, out culture);

I would be really appreciate for help because I even don't know how to consume this problem in proper way ....
If there is already information on forum please tell me where as I'm unable to find it.

Thanks
Karol

David Tchepak

unread,
Jul 17, 2014, 5:42:39 PM7/17/14
to nsubs...@googlegroups.com
Hi Karol,

NSubstitute can't mock static methods, so if you want to use NSub for this you'll need to rewrite the original class, or wrap the functionality in a new class that you can mock. Because some extra code is required, I'd probably lose the output params as well (they're a pain to mock, and I like getting data out from the return value where possible). Here's a quick example of the wrapping the existing behaviour and mocking that wrapper.

public class UserDetails {
  public readonly int? UserID;
  public readonly string UserName;
  public readonly string FullName;
  public readonly string Culture;
  public UserDetails(/* constructor fields here */) { /* init fields here */ }
}

public interface IGetUserDetails {
  UserDetails GetDetails();
}

public class GetUserDetailsFromAcceptanceFlow : IGetUserDetails {
  /* init output variables here */
  AcceptanceFlow.GetLoggedInUserNameAndId(out userId, out userName, out userFullName, out culture); // <-- call original static method
  return new UserDetails(userId, userName, ... );
}

[Test]
public void TestSomeOtherClassDisplaysLoggedInUser() {
  var user = new UserDetails(1, "abc", "Karol", "");
  var view = Substitute.For<ISomeView>();
  var getDetails = Substitute.For<IGetUserDetails>();
  getDetails.GetDetails().Returns(user);

  var otherClass = new OtherClass(getDetails, view);
  otherClass.Load();

  Assert.That(view.LoggedInUser, Is.EqualTo(user.FullName))l;
}

Hope this helps.
Regards,
David



--
You received this message because you are subscribed to the Google Groups "NSubstitute" group.
To unsubscribe from this group and stop receiving emails from it, send an email to nsubstitute...@googlegroups.com.
To post to this group, send email to nsubs...@googlegroups.com.
Visit this group at http://groups.google.com/group/nsubstitute.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages