Question

I am trying to use Shim to test one of my private method in this class called DataSyncCore. Apologies if this is too trivial as i am new to shims and can't figure out why this is giving me an error saying "The property or indexer GetEnvironmentString cannot be used in this context as it is lacking an accessor. How can this be fixed?

//Method to be tested inside DataSyncCore Class 
private Environments GetEnvironment(string env)
{
   string environment = env.ToLower();

   switch (environment)
   {
      case "dev":
         return Environments.Dev;
      case "qc":
         return Environments.QC;
      case "uat":
         return Environments.UAT;
      case "prod":
         return Environments.PROD;
      default:
         return Environments.Dev;
   }
}

This is my unit test:

[TestMethod]
public void DataSyncCore_GetsEnvironment_Succeeded()
{
   using (ShimsContext.Create())
   {
      var core = new ShimDataSyncCore()
      {
         GetEnvironmentString = (dev) =>
         {
            return Environments.Dev;
         }
      };
      Assert.AreEqual(Environments.Dev, core.GetEnvironmentString("dev"));
   }
}
Was it helpful?

Solution

If you cannot make the class public, you can still use Activator.CreateInstance:

var anInstance = (YourPrivateClass)Activator.CreateInstance(typeof(YourPrivateClass), true);

Or, you could mark the method as internal and set InternalsVisibleTo attribute in your assemblyinfo if you want/need to test that method directly.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top