mercredi 25 novembre 2015

How to refactor async MVC controller with async WCF calls for unit testing

I have inherited some MVC code that I would like to refactor to assist unit testing. The web service is provided by a third party so I have no control of it.

The current code looks something like this

    public void CreateUser(User user)
    {
        using (UserClient proxy = new UserClient())
        {
            AsyncManager.OutstandingOperations.Increment();
            CreateUser request = new CreateUser();

            request.EmailAddress = user.Username;
            request.Password = user.Password;

            proxy.CreateUserCompleted += (object sender, CreateUserCompletedEventArgs e) =>
            {
                // TODO Some other action

                AsyncManager.OutstandingOperations.Decrement();
            };
            proxy.CreateUserAsync(request);
        }
    }

As you can see there is a concrete dependency on the client which has been generated through Service->Add Reference which makes unit testing not possible. My first thought, was to use dependency injection and inject the interface that is generated by the client proxy.

However, this presented a problem in that the interface does not contain any definitions for async methods such as CreateUserAsync so I was unable to use it in my unit tests

I did consider making an async proxy interface as below interface

   public interface IUserServiceAsync{
        CreateUserAsync(UserRequest request);
   }

and then have the concrete implementation to wrap calls to the ServiceClient. However, I don't really like this and I am worried that it will be hard to keep this in line with changes in the contract carried out by the 3rd party.

At this point, I need some guidance on how I can move further forward in refactoring this for unit testing?

Aucun commentaire:

Enregistrer un commentaire