简体   繁体   中英

dependecy injection and unit testing - static helper methods or private instance methods

From unit testing and dependency injection point of view, what's the usual adopted norm when it comes to helper methods?

Here is my example situation:

public class GoodiesController : Controller
{
   private IMyContext _context;

   public GoodiesController(IMyContext context)
   {
      _context = context
   }

   public async Task<IAction> GetThoseGoodies()
   { 
       if(YouLikeThemThisWay(Request.Path))
        {
           var result = await _context.GoGetThemThisWay()
        } else { }
    }

My question is am I better off with YouLikeThemThisWay(string path) as a static helper in some class or as a private instance method? Assuming I might have a couple of the likes of YouLikeThemThisWay ?

It really depends on what your YouLikeThemThisWay(string path) method does. My rules for using a static method or as follows:

  1. Does it require a non-primitive dependency? If so, don't use static.
  2. Does it affect the state of the application? If so, don't use static.
  3. Does it extend the functionality of a class or type you do not have access to internally (IE BCL classes or primatives)? If so use a static extension!
  4. Will it impact unit tests--as in make them more difficult--if I cannot mock the routine? If no, then make it static!
  5. Will it be used by more than one type or class? If so that it makes it a better candidate for static!
  6. Does the routine perform some sort of IO, like calling a database or the filesystem? If so, I would not make it static.

Basically, small helper functions that are easily tested and don't affect state or usually OK to make static. If there is state involved, the routine requires a dependency that you would normally inject, or the routine is making IO or IPC calls then do not make it static.

One caveat to the dependency issue is technically you could use method injection to handle the dependencies, but I like to keep it simple. Your method is probably OK to be static.

Reuse is a big factor in statics too. If the routine will only be used in one class, it may be pointless to make static. Most of my static methods live in helper classes that are easily accessed anywhere.

EDIT: Note that I usually require most or all of those five rules to favor statics in order for me to even consider making something static.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM