0

How can I moq the following so it returns a new Guid();

private void CheckSomething(){
...
    user = CustomerContext.Current.User; // returns Guid

CustomerContext is taken from a third party library and it is not injected into my class.

is there any way to do it?

ShaneKm
  • 20,823
  • 43
  • 167
  • 296
  • You must create a wrapper of that third party library. – CodeNotFound Feb 08 '16 at 19:41
  • Sounds like it should be injected into the class so it can be mocked. (Possibly wrapped in an interface, depending on how mockable it is.) Basically, your unit testing is indicating to you that the code is coupled to a dependency. That should be corrected. – David Feb 08 '16 at 19:41
  • how do I create a wrapper? – ShaneKm Feb 08 '16 at 19:42
  • 1
    @ShaneKm: A class with pass-through operations to the 3rd party object should do the trick. Have that class implement an interface, then use that interface to create mocks. The code being tested should rely on the interface (wrapper), not on the 3rd party object. – David Feb 08 '16 at 19:42
  • But this would require me to modify the method tested so that instead of user = CustomerContext => I would change it to CustomerContextWrapper.Current.User. Correct? I don't really want to modify existing code in that method. Is that the only option? – ShaneKm Feb 08 '16 at 19:55
  • @ShaneKm I believe that is the only option. Writing testable code requires a certain amount of planning up front - loose coupling, DI, not relying so heavily on static methods, etc. Without that initial planning/implementation up front, you'll likely have to do some refactoring. – Kritner Feb 08 '16 at 19:59
  • @ShaneKm related: http://stackoverflow.com/questions/1214178/moq-unit-testing-a-method-relying-on-httpcontext – Kritner Feb 08 '16 at 20:01

1 Answers1

1

I did this.

public class UserContextWrapper : ICustomUserContext
{
    public Guid UserGuid
    {
        get { return CustomerContext.Current.User; }
    }
}

Then In my code I had to modify original to:

private void CheckSomething(){
...
    user = UserContextWrapper.UserGuid ; // returns Guid

Now I'm able to mock. I'm simply injecting ICustomerUserContext into my class and I have mapped UserContextWrapper to ICustomUserContext in IoC Container.

ShaneKm
  • 20,823
  • 43
  • 167
  • 296