Testing Internals Methods

Overview

How to Unit test Internals Methods


Downloads

You can download the the files..
Calculator.cs

CalculatorTests.cs


Files

Calculator.cs
using System.Runtime.CompilerServices;

[assembly: InternalsVisibleTo("Code.UnitTest")]

namespace Code
{
    public class Calculator
    {
        public string ProcessCalculation(string line)
        {
            string[] parts = line.Split(new[] { '+', '-' });

            float valueA = float.Parse(parts[0]);
            float valueB = float.Parse(parts[1]);

            if (line.Contains('+'))
                return Add(valueA, valueB).ToString();

            if (line.Contains('-'))
                return Sub(valueA, valueB).ToString();

            return "ERROR:";
        }

        internal float Add(float a, float b)
        {
            return a + b;
        }

        internal float Sub(float a, float b)
        {
            return a - b;
        }
    }
}


CalculatorTests.cs
namespace Code.UnitTest
{
    public class Tests
    {
        [TestCase("1+2", "3")]
        [TestCase("123-23", "100")]
        [TestCase("1-2", "-1")]
        public void ShouldAddNumbers(string process, string expectedResult)
        {
            var code = new Calculator();
            var result = code.ProcessCalculation(process);

            Assert.That(result, Is.EqualTo(expectedResult));
        }

        [Test]
        public void ShouldAddReturnAddedValues()
        {
            var code = new Calculator();
            var result = code.Add(1, 1);

            Assert.That(result, Is.EqualTo(2));
        }

        [Test]
        public void ShouldSubReturnSubValues()
        {
            var code = new Calculator();
            var result = code.Sub(1, 1);

            Assert.That(result, Is.EqualTo(0));
        }
    }
}