0

I have the following code:

        /// <summary>
        /// Gets the connection string.
        /// </summary>
        private readonly string _connectionString = ConfigurationManager.ConnectionStrings["Database"].ConnectionString;

        /// <summary>
        /// Instantiates a new instance of <see cref="DapperReaderWrapper"/> object.
        /// </summary>
        private readonly IDapperReaderWrapper _dapperReaderWrapper = new DapperReaderWrapper();

        /// <summary>
        /// Retrieves a list of admins from the database.
        /// </summary>
        /// <returns>List of admins.</returns>
        public List<Admin> RetrieveListOfAdmins()
        {
            var adminDatabaseReader = new AdminDatabaseReader(_connectionString, _dapperReaderWrapper);
            return adminDatabaseReader.GetAll();
        }

I am trying to unit test my "RetrieveListOfAdmins" method near the bottom. Here is my unit test class:

        private string _connectionString;
        private Mock<IDapperReaderWrapper> _mockDapperReaderWrapper;
        private DatabaseReaderGateway _databaseReaderGateway;

        [TestInitialize]
        public void Initialize()
        {
            _connectionString = DatabaseShared.GetTestingConfigurationFile();
            _mockDapperReaderWrapper = new Mock<IDapperReaderWrapper>();
            _databaseReaderGateway = new DatabaseReaderGateway();
        }

        [TestMethod]
        [TestCategory("Business Test")]
        public void DatabaseReaderGateway_RetrieveListOfAdmins_WhenCallingDatabaseReader_ShouldReturnListOfAdmins()
        {
            // Arrange
            var expectedListOfAdmins = DatabaseShared.MockSetupListOfAdmins();
            SetupMockDapperReaderWrapper("AllAdmins", expectedListOfAdmins);

            // Act
            var actualListOfAdmins = _databaseReaderGateway.RetrieveListOfAdmins();

            // Assert
            Assert.AreEqual(expectedListOfAdmins, actualListOfAdmins, "We were expecting lists to be equal, but they were not.");
            Assert.IsTrue(actualListOfAdmins.Count > 0, "We were expecting a list of admins, but got back zero.");
        }

        /// <summary>
        /// Sets up the dapper reader wrapper and returns a list of items.
        /// </summary>
        /// <typeparam name="T">Generic type item.</typeparam>
        /// <param name="query">Sql Query.</param>
        /// <param name="listOfItems">List of items.</param>
        private void SetupMockDapperReaderWrapper<T>(string query, List<T> listOfItems)
        {
            _mockDapperReaderWrapper.Setup(wrapper => wrapper.Query<T>(It.Is<IDbConnection>(db => db.ConnectionString == _connectionString), query, CommandType.StoredProcedure))
                                    .Returns(listOfItems);
        }

When I try to run the test, I get the following error on the ConfigurationManager in my class: "Object reference not set to an instance of an object."

Here is my app.config that is in all of my solutions.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <connectionStrings>
        <add name="Database" connectionString="Data Source=DESKTOP-IKINKC8\SQLEXPRESS;Initial Catalog=Database;Integrated Security=True;" />
    </connectionStrings>
</configuration>

And here is the code I have for getting the connection string for my test projects:

        /// <summary>
        /// Gets the configuration file for testing projects.
        /// </summary>
        /// <returns>Connection string.</returns>
        public static string GetTestingConfigurationFile()
        {
            ExeConfigurationFileMap configFileMap = new()
            {
                ExeConfigFilename = "App.config"
            };

            var config = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None);

            var section = (ConnectionStringsSection)config.GetSection("connectionStrings");
            var connectionStringCollection = section.ConnectionStrings;

            var connectionString = string.Empty;
            foreach (var connection in connectionStringCollection)
            {
                if (!connection.ToString().Contains("DESKTOP"))
                {
                    continue;
                }

                connectionString = connection.ToString();
            }

            return connectionString;
        }

Does anyone know why this might be? I have an app.config in my testing project as well as my project containing my class.

  • Do you have configurations in the test project? – Akshay Bheda Oct 11 '21 at 00:14
  • It could be one of several issues: You didn't add app.config to your Test project. You didn't add connection string in your app.config. – Akshay Bheda Oct 11 '21 at 00:15
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – CoolBots Oct 11 '21 at 01:42
  • I have app.configs in all my projects and the connection string is also in all of them. @AkshayBheda – James McKinney Oct 11 '21 at 13:44

1 Answers1

0

It could be one of below issues:

  • You didn't add app.config to your Test project.
  • You didn't add connection string in your app.config.
Akshay Bheda
  • 773
  • 1
  • 6
  • 22