V
V
Valera Figol2017-06-09 18:38:15
C++ / C#
Valera Figol, 2017-06-09 18:38:15

How can you mock this code?

There is the following code:

public class UploadBase
    {
        protected string userId;
        protected string containerName;
        protected int maxLengthFile;

        protected CloudBlobContainer container;
        protected static Logger logger = LogManager.GetLogger("UploadFile");

        private static string cacheControl = "public, max-age=7776000";

        public UploadBase(string containerName) : this(string.Empty, containerName)
        {
            maxLengthFile = 21504;
        }

        public UploadBase(string userId, string containerName)
        {
            if (string.IsNullOrEmpty(containerName))
                new ArgumentNullException(containerName);

            this.userId = userId;
            this.containerName = containerName;

            // Receiving Account storage 
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"].ToString());

            // Create Blob client 
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            // To get conteiner reference 
            container = blobClient.GetContainerReference(this.containerName);

            if (!container.Exists())
            {
                container.CreateIfNotExists();
                container.SetPermissions(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
            }
        }

without mock throws an error about NullReferenceException on this line:
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnectionString"].ToString());

please tell me how to get around this

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fat Lorrie, 2017-06-09
@Kamrit

Obviously, you need to isolate the ConfigurationManager, wrapping it in a "facade" IConfigurationwith the appropriate access methods, and then mock it.

interface IConfiguration
{
    string ConnectionString { get; }
}

class AppSettingsConfiguration: IConfiguration
{
    public string ConnectionString
    {
        get
        { 
            return ConfigurationManager.AppSettings["ConnectionString"];
        }
    }
}

var config = new Mock<IConfiguration>();
config.Setup(x => x.ConnectionString).Returns("test value");

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question