Home > Software engineering >  Mock async generic method from base class
Mock async generic method from base class

Time:01-27

I've classes similar to this:

public class Class1
    {
        private readonly IClient _client;

        public Class1(Configuration config, CacheManager cacheManager)
        {
            _client = new Client(config, cacheManager);
        }

        protected async Task<T> PostAndDeserialize<T>(string param1, object param2)
        {
            var result = await _client.PostSomething(param1, param2);

            return JsonConvert.DeserializeObject<T>(await result.Content.ReadAsStringAsync());
        }
    }

    public class Class2 : Class1
    {
        public Class2(Configuration config, CacheManager cacheManager) : base(config, cacheManager)
        {
        }

        public async Task<Response> CreateSomething(Request request)
        {
            //do something
            var result = PostAndDeserialize<Result>("test", test);

            return new Response { Id = result.Id };
        }
    }

I need to write unit test for Class2, CreateSomething method - how do I mock PostAndDeserialize method ? I've tried and find a way to mock protected generic class from base class but I couldn't find any help with it :( Or maybe it should be done in some other way ?(I'm new to unit test). Any help is appreciated.

I've tried using Protected() and calling method by it's name but as it's generic method it didn't work.

CodePudding user response:

Your options are:

  1. Rewrite the code so it is testable. This can be done by making the method virtual or by using composition instead of inheritance and program to an interface instead of an implementation.
  2. Purchase Visual Studio Enterprise which includes Microsoft Fakes. Or some other third-party solution.
  • Related