C#C
C#3y ago
6 replies
electronic heartbreak.

Testing private methods

Hey there, I have the following code:
public class Input
    { 
        public string SelectLevel() {
            string level;
            bool isValid = false;

            do
            {
                Console.WriteLine("Selecteer een level");
                level = Console.ReadLine();

                if (IsInputValid(level))
                {
                    isValid = true;
                }
            }
            while (!isValid);
            
            return level;
        }

        private static bool IsInputValid(string level)
        {
            return !string.IsNullOrWhiteSpace(level) && level.Length > 5 && level.Contains('.');
        }

        public void AskInput()
        {
            
        }
    }
}

I want to unit test this code using NUnit, When creating a Setup and initializing the class these 2 methods are in, and trying to write a test for the IsInputValid I see that I cant test private methods. However, it feels needed to test that method. I worked around the issue doing the following, but this feel very ugly.
        [Test]
        public void IsInputValid_ReturnsTrue()
        {
            // Arrange
            MethodInfo isInputValidMethod = typeof(Input)
                .GetMethod("IsInputValid",
                           BindingFlags.NonPublic | BindingFlags.Static);

            string level = "level1.txt";
            // Act
            bool result = (bool)isInputValidMethod.Invoke(null, new object[] { level });

            // Assert
            Assert.That(result, Is.True);
        }


If you have a solution for this or adivce, I am curious to know!
Was this page helpful?