Question

In: Computer Science

Subject- ( App Development for Web) ( language C#, software -visual studio) I have created a...

Subject- ( App Development for Web) ( language C#, software -visual studio)

I have created a 'Calculator' named program in visual studio. This is the main console program(Program.cs) shown below. Then i have created a "CaculatorLibrary" named project by adding the project from FILE--->ADD--->NEW PROJECT. Then i selected library and selected classLibrary(.NETcore). The programs for both are given below. There are no errors in the program. Now the requirement is to build unit test project within this project that will perform atleast 10 tests.The tests must be like add rwo positive numbers,multiply two positive numbers and so on ... . This test project will also be created by FILE--->ADD--->NEW PROJECT.But here instead of library select test .

Program.cs
using CalculatorLibrary;
using System;

namespace CalculatorProgram
{
  

class Program
{
static void Main(string[] args)
{
bool endApp = false;
// Display title as the C# console calculator app.
Console.WriteLine("Console CalculatorProgram in C#\r");
Console.WriteLine("------------------------\n");
Calculator Calculator = new Calculator();
while (!endApp)
{
// Declare variables and set to empty.
string numInput1 = "";
string numInput2 = "";
double result = 0;

// Ask the user to type the first number.
Console.Write("Type a number, and then press Enter: ");
numInput1 = Console.ReadLine();

double cleanNum1 = 0;
while (!double.TryParse(numInput1, out cleanNum1))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput1 = Console.ReadLine();
}

// Ask the user to type the second number.
Console.Write("Type another number, and then press Enter: ");
numInput2 = Console.ReadLine();

double cleanNum2 = 0;
while (!double.TryParse(numInput2, out cleanNum2))
{
Console.Write("This is not valid input. Please enter an integer value: ");
numInput2 = Console.ReadLine();
}

// Ask the user to choose an operator.
Console.WriteLine("Choose an operator from the following list:");
Console.WriteLine("\ta - Add");
Console.WriteLine("\ts - Subtract");
Console.WriteLine("\tm - Multiply");
Console.WriteLine("\td - Divide");
Console.Write("Your option? ");

string op = Console.ReadLine();

try
{
result = Calculator.DoOperation(cleanNum1, cleanNum2, op);
if (double.IsNaN(result))
{
Console.WriteLine("This operation will result in a mathematical error.\n");
}
else Console.WriteLine("Your result: {0:0.##}\n", result);
}
catch (Exception e)
{
Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
}

Console.WriteLine("------------------------\n");

// Wait for the user to respond before closing.
Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
if (Console.ReadLine() == "n") endApp = true;

Console.WriteLine("\n"); // Friendly linespacing.
}
return;
}
}
}

CalculatorLibrary.cs

using System.Diagnostics;
using System;
using System.IO;

namespace CalculatorLibrary
{
public class Calculator
{
public Calculator()
{
StreamWriter logFile = File.CreateText("calculator.log");
Trace.Listeners.Add(new TextWriterTraceListener(logFile));
Trace.AutoFlush = true;
Trace.WriteLine("Starting Calculator Log");
Trace.WriteLine(String.Format("Started {0}", System.DateTime.Now.ToString()));
}
public double DoOperation(double num1, double num2, string op)
{
double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.

// Use a switch statement to do the math.
switch (op)
{
case "a":
result = num1 + num2;
Trace.WriteLine(String.Format("{0} + {1} = {2}", num1, num2, result));
break;
case "s":
result = num1 - num2;
Trace.WriteLine(String.Format("{0} - {1} = {2}", num1, num2, result));
break;
case "m":
result = num1 * num2;
Trace.WriteLine(String.Format("{0} * {1} = {2}", num1, num2, result));
break;
case "d":
// Ask the user to enter a non-zero divisor.
if (num2 != 0)
{
result = num1 / num2;
Trace.WriteLine(String.Format("{0} / {1} = {2}", num1, num2, result));
}
break;
// Return text for an incorrect option entry.
default:
break;
}
return result;
}
  
}
}

Solutions

Expert Solution

Hi,

I have modified some code and below are the updated files:

Namespace - calculatorlibrary

ClassName - Calculator


using System;
using System.Diagnostics;
using System.IO;

namespace calculatorlibrary
{
    public class Calculator
    {
        public Calculator()
        {
            StreamWriter logFile = File.CreateText("calculator.log");
            Trace.Listeners.Add(new TextWriterTraceListener(logFile));
            Trace.AutoFlush = true;
            Trace.WriteLine("Starting Calculator Log");
            Trace.WriteLine(String.Format("Started {0}", System.DateTime.Now.ToString()));
        }

        public double DoOperation(double num1, double num2, string op)
        {
            double result = double.NaN; // Default value is "not-a-number" which we use if an operation, such as division, could result in an error.

            // Use a switch statement to do the math.
            switch (op)
            {
                case "a":
                    result = num1 + num2;
                    Trace.WriteLine(String.Format("{0} + {1} = {2}", num1, num2, result));
                    break;
                case "s":
                    result = num1 - num2;
                    Trace.WriteLine(String.Format("{0} - {1} = {2}", num1, num2, result));
                    break;
                case "m":
                    result = num1 * num2;
                    Trace.WriteLine(String.Format("{0} * {1} = {2}", num1, num2, result));
                    break;
                case "d":
                    // Ask the user to enter a non-zero divisor.
                    if (num2 != 0)
                    {
                        result = num1 / num2;
                        Trace.WriteLine(String.Format("{0} / {1} = {2}", num1, num2, result));
                    }
                    break;
                // Return text for an incorrect option entry.
                default:
                    break;
            }
            return result;
        }
    }
}

If you build this code then you will find the DLL - calculatorlibrary.dll in the bin folder. This DLL need to add in the reference in our CalculatorProgram Project

I have creted new Project - CalculatorProgram as console project. You can see that I have added the calculatorlibrary reference in the using statement - using calculatorlibrary;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using calculatorlibrary;
namespace CalculatorProgram
{
    class Program
    {
        static void Main(string[] args)
        {
            bool endApp = false;
            // Display title as the C# console calculator app.
            Console.WriteLine("Console Calculator in C#\r");
            Console.WriteLine("------------------------\n");
            Calculator calculator = new Calculator();

            while (!endApp)
            {
                // Declare variables and set to empty.
                string numInput1 = "";
                string numInput2 = "";
                double result = 0;

                // Ask the user to type the first number.
                Console.Write("Type a number, and then press Enter: ");
                numInput1 = Console.ReadLine();

                double cleanNum1 = 0;
                while (!double.TryParse(numInput1, out cleanNum1))
                {
                    Console.Write("This is not valid input. Please enter an integer value: ");
                    numInput1 = Console.ReadLine();
                }

                // Ask the user to type the second number.
                Console.Write("Type another number, and then press Enter: ");
                numInput2 = Console.ReadLine();

                double cleanNum2 = 0;
                while (!double.TryParse(numInput2, out cleanNum2))
                {
                    Console.Write("This is not valid input. Please enter an integer value: ");
                    numInput2 = Console.ReadLine();
                }

                // Ask the user to choose an operator.
                Console.WriteLine("Choose an operator from the following list:");
                Console.WriteLine("\ta - Add");
                Console.WriteLine("\ts - Subtract");
                Console.WriteLine("\tm - Multiply");
                Console.WriteLine("\td - Divide");
                Console.Write("Your option? ");

                string op = Console.ReadLine();

                try
                {
                    //We need to call the DoOperation function using Class instance which we have created.
                    //Only static Methods can be called using ClassName like ClassName.MethodName
                    result = calculator.DoOperation(cleanNum1, cleanNum2, op);
                    if (double.IsNaN(result))
                    {
                        Console.WriteLine("This operation will result in a mathematical error.\n");
                    }
                    else Console.WriteLine("Your result: {0:0.##}\n", result);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Oh no! An exception occurred trying to do the math.\n - Details: " + e.Message);
                }

                Console.WriteLine("------------------------\n");

                // Wait for the user to respond before closing.
                Console.Write("Press 'n' and Enter to close the app, or press any other key and Enter to continue: ");
                if (Console.ReadLine() == "n") endApp = true;

                Console.WriteLine("\n"); // Friendly linespacing.
            }
            return;
        }
    }
}

When you run this then observe the below output:

Then Created new Unit Test Case Project - UnitTestProjectCalculator

Please see the below code in the for the Class - UnitTest1

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using calculatorlibrary;
namespace UnitTestProjectCalculator
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethodAddPositiveNumbers()
        {
            int iFIrstNumber = 1;
            int iSecondNumber = 2;

            Calculator objCalculator = new Calculator();
           Assert.AreEqual( objCalculator.DoOperation(iFIrstNumber, iSecondNumber,"a"),3);
        }

        [TestMethod]
        public void TestMethodAddNegativeNumbers()
        {
            int iFIrstNumber = -1;
            int iSecondNumber = -5;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "a"), -6);
        }

        [TestMethod]
        public void TestMethodAddPositiveNegativeNumbers()
        {
            int iFIrstNumber = 1;
            int iSecondNumber = -5;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "a"), -4);
        }

        [TestMethod]
        public void TestMethodSubPositiveNumbers()
        {
            int iFIrstNumber = 3;
            int iSecondNumber = 2;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "s"), 1);
        }

        [TestMethod]
        public void TestMethodSubNegativeNumbers()
        {
            int iFIrstNumber = -3;
            int iSecondNumber = -25;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "s"), 22);
        }

        [TestMethod]
        public void TestMethodSubPositiveNegativeNumbers()
        {
            int iFIrstNumber = -3;
            int iSecondNumber = 25;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "s"), -28);
        }

        [TestMethod]
        public void TestMethodMulPositiveNumbers()
        {
            int iFIrstNumber = 3;
            int iSecondNumber = 2;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "m"), 6);
        }

        [TestMethod]
        public void TestMethodMulNegativeNumbers()
        {
            int iFIrstNumber = -3;
            int iSecondNumber = -2;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "m"), 6);
        }

        [TestMethod]
        public void TestMethodDivPositiveNumbers()
        {
            int iFIrstNumber = 3;
            int iSecondNumber = 3;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "d"), 1);
        }

        [TestMethod]
        public void TestMethodDivNegativeNumbers()
        {
            int iFIrstNumber = -3;
            int iSecondNumber = -3;

            Calculator objCalculator = new Calculator();
            Assert.AreEqual(objCalculator.DoOperation(iFIrstNumber, iSecondNumber, "d"), 1);
        }
    }
}

:

You need add the Project Reference here as well to call the DoOperation() Method from the Calculator Class (You can see that I have imported the same using - using calculatorlibrary;)

Here you can see that I have created 10 different Test Cases and one by one I have tested that they are running.

Here we have used Streamwriter Class in the Constructor and so that we have to run the Test case one by one. If you wanted to run all the Test cases at once then you need comment the code in the constructor, need to build this Project, then need to add the Reference of that newly build dll in to the - CalculatorProgramm and UnitTestCaseProjectCalculatorProject and then it will run all the 10 Test cases once at a time.


Related Solutions

USING VISUAL STUDIO 2017, LANGUAGE VISUAL C# I have struggled on this program for quite some...
USING VISUAL STUDIO 2017, LANGUAGE VISUAL C# I have struggled on this program for quite some time and still can't quite figure it out. I'm creating an app that has 2 textboxes, 1 for inputting customer name, and the second for entering the number of tickets the customer wants to purchase. There are 3 listboxes, the first with the days of the week, the second with 4 different theaters, and the third listbox is to display the customer name, number...
Make a Program in Visual Studio / Console App (.NET Framework) # language Visual Basic You...
Make a Program in Visual Studio / Console App (.NET Framework) # language Visual Basic You will be simulating an ATM machine as much as possible Pretend you have an initial deposit of 1000.00. You will Prompt the user with a Main menu: Enter 1 to deposit Enter 2 to Withdraw Enter 3 to Print Balance Enter 4 to quit When the user enters 1 in the main menu, your program will prompt the user to enter the deposit amount....
C# ( asp.net ) 2019 visual studio I have a dropdown option. If I choose "date"...
C# ( asp.net ) 2019 visual studio I have a dropdown option. If I choose "date" option, I get to enter list of dates like 02/08/1990, 06/14/1890 in (mm/dd/YYYY) format. How can I sort these dates in ascending order?. Can you provide me some code. Thank you
C# ( asp.net ) 2019 Visual Studio I have a dropdown where you can select (...
C# ( asp.net ) 2019 Visual Studio I have a dropdown where you can select ( integer, string, date ) After selecting the desired dropdown option, user can input a list of inputs. For example; for integer: 2,5,7,9,1,3,4 And then , I have a 'sort' button Can you please help me with the code behind for sorting them( For integer, string, and date ) Thank you.
Programming Language: C# CheckingAccount class You will implement the CheckingAccount Class in Visual Studio. This is...
Programming Language: C# CheckingAccount class You will implement the CheckingAccount Class in Visual Studio. This is a sub class is derived from the Account class and implements the ITransaction interface. There are two class variables i.e. variables that are shared but all the objects of this class. A short description of the class members is given below: CheckingAccount Class Fields $- COST_PER_TRANSACTION = 0.05 : double $- INTEREST_RATE = 0.005 : double - hasOverdraft: bool Methods + «Constructor» CheckingAccount(balance =...
Write a C-based language program in visual studio that uses an array of structs that stores...
Write a C-based language program in visual studio that uses an array of structs that stores student information including name, age, GPA as a float, and grade level as a string (e.g., “freshmen,”). Write the same program in the same language without using structs.
Create a new website using C# & ASP.Net in Visual Studio: 1. Create a web page...
Create a new website using C# & ASP.Net in Visual Studio: 1. Create a web page to access a database and display the data from a table by providing an SQL statement. Create the page with these requirements:     create label, textbox and button     the textbox will capture the SQL statement     the button will process the statement and display the results 2. Add necessary data access pages to your project. 3. Display the data in Gridview
ONLY USE VISUAL STUDIO (NO JAVA CODING) VISUAL STUDIO -> C# -> CONSOLE APPLICATION In this...
ONLY USE VISUAL STUDIO (NO JAVA CODING) VISUAL STUDIO -> C# -> CONSOLE APPLICATION In this part of the assignment, you are required to create a C# Console Application project. The project name should be A3<FirstName><LastName>P2. For example, a student with first name John and Last name Smith would name the project A1JohnSmithP2. Write a C# (console) program to calculate the number of shipping labels that can be printed on a sheet of paper. This program will use a menu...
Create a question bank. The language is visual studio c++. Description: Question bank computerizes the MCQ...
Create a question bank. The language is visual studio c++. Description: Question bank computerizes the MCQ based exams.It takes input from a file having questions and their answers and presents randomly before the exam takers. Required skill set: OOP, STL(Vector), Arrays and file handling
Objectives: 1. To get familiar with C# programming language 2. To get familiar with Visual Studio...
Objectives: 1. To get familiar with C# programming language 2. To get familiar with Visual Studio development environment 3. To practice on writing a C# program Task 1: Create documentation for the following program which includes the following: a. Software Requirement Specification (SRS) b. Use Case Task 2: Write a syntactically and semantically correct C# program that models telephones. Your program has to be a C# Console Application. You will not implement classes in this program other than the class...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT