MS Unit testing (C# .net)

Hi Sir, Hope you are doing well!

I need some help in MS-Unit testing in C# .net program, I watched all of your youtube videos but…

So, below is my question, Please help!

Write Automated MS-Unit Test in C#.NET for the following C#.NET program. The program converts a decimal value into binary?

using System;
namespace BinaryClass
{
    class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine("Binary Value of 4 = "+p.IntToBinaryString(4));
        }
        public string IntToBinaryString(int number)
        {
            const int mask = 1;
            var binary = string.Empty;
            while (number > 0)
            {
                binary = (number & mask) + binary;
                number = number >> 1;
            }
            return binary;
        }
    }
}
2 Likes

You need to create a MSTest project whose main class contains the below code to run

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject1
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            Console.WriteLine("Hello World!");
            BinaryClass.BinaryConverter p = new BinaryClass.BinaryConverter();
            string expected = "100";
            string actual = p.IntToBinaryString(4);
            Assert.AreEqual(expected, actual);
            Console.WriteLine("Binary Value of 4 = " + p.IntToBinaryString(4));
        }
    }
}

Then you would create another class that contains a code for converting int to binary

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BinaryClass
{
    public class BinaryConverter
    {
        public string IntToBinaryString(int number)
        {
            const int mask = 1;
            var binary = string.Empty;
            while (number > 0)
            {
                binary = (number & mask) + binary;
                number = number >> 1;
            }
            return binary;
        }
    }
}

Then run the code using Test Explorer

4 Likes