jeudi 25 février 2021

How to write Xunit test case of factory design pattern code block which is tightly coupled?

I would like to write xunit test case of below method. Could you please suggest alternate design so i can write xunit test case with minimum change in my current project.

public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
        {
            using (var tracer = new Tracer("AssetController", "Index"))
            {
                
                RemoveReturnUrl();
                ViewBag.JobId = id;
                var response = ContextFactory.Current.GetDomain<AssetDomain>().GetAssetFilterAsync(id, 
 CurrentUser.CompanyId, filter); // Not able write unit test case , please suggest alternate design. 
                return View("View", response);
            }
        } 

current design is as follow

 public interface IDomain
            {
            }

 public interface IContext
        {
            D GetDomain<D>() where D : IDomain;
    
            string ConnectionString { get; }
        }

 public class ApplicationContext : IContext
    {
        public D GetDomain<D>() where D : IDomain
        {
            return (D)Activator.CreateInstance(typeof(D));
        }

        public string ConnectionString
        {
            get
            {
                return "DatabaseConnection";
            }
        }
    }

 public class ContextFactory
        {
            private static IContext _context;
    
            public static IContext Current
            {
                get
                {
                    return _context;
                }
            }
    
            public static void Register(IContext context)
            {
                _context = context;
            }
        }

//var response = ContextFactory.Current.GetDomain**< AssetDomain >**().GetAssetFilterAsync(id, CompanyId, filter);
This line serve purpose to call specific class method i.e GetAssetFilterAsync from AssetDomain. Although it is very handy and widely used in our application but due to design issue i am not able to write unit test case.

Could you please suggest design so with the minimum change we can write unit test case.

Aucun commentaire:

Enregistrer un commentaire