Unit test takes more time to do a subtraction - c#

I was trying Unit Tests by writing simple examples.
Tested code:
public class Operations
{
public static double Subtraction(double number1, double number2)
{
return number1 - number2;
}
public static double Addition(double number1, double number2)
{
return number1 + number2;
}
public static double Division(double number1, double number2)
{
if (number2 != 0)
{
return number1 / number2;
}
else
{
return number1;
}
}
public static double Multiplication(double number1, double number2)
{
return number1 * number2;
}
}
Test Methods:
[TestClass()]
public class OperationsTests
{
[TestMethod()]
public void SubtractionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(-10, result);
}
[TestMethod()]
public void SubtractionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void SubtractionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Subtraction(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void AdditionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void AdditionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void AdditionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Addition(number1, number2);
Assert.AreEqual(20, result);
}
[TestMethod()]
public void DivisionTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Division(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void DivisionTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Division(number1, number2);
Assert.AreEqual(10, result);
}
[TestMethod()]
public void DivisionTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Division(number1, number2);
Assert.AreEqual(1, result);
}
[TestMethod()]
public void MultiplicationTest1()
{
double number1 = 0;
double number2 = 10;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void MultiplicationTest2()
{
double number1 = 10;
double number2 = 0;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(0, result);
}
[TestMethod()]
public void MultiplicationTest3()
{
double number1 = 10;
double number2 = 10;
double result = Operations.Multiplication(number1, number2);
Assert.AreEqual(100, result);
}
}
Every test is executing without any error but i noticed that SubtractionTest1 took always 7-8-9ms while the others take less than 1ms, can you explain me why?
Tests result:

MSTest will randomise the order that unit tests run in, as this can sometimes expose bugs in timing or shared state.
Which ever test you run first will take longer because it will be the one required to both JIT compile each of your methods and types and if any of those types have static initialisation to perform then this will also trigger.
I had a unit test suite where the first test would always take approximately 0.5s because I was initialising both the dependency injection and mocking frameworks. Every test post initialisation would take approximately 1ms to 2ms. So the behaviour you see here is totally normal.
For performance testing you must average your results and discard your first result to remove intialisation time from them. You should also test your initialisation speed if that is relevant to your application, but it's usually irrelevant for a server that boots once then stays online and ready.

Related

Accessing values from a method to another method

How do i access values from ReadInput() method so that i can use num1 and num2 for addition in Addition() method
public class HelloWorld
{
public void ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
}
public void Addition()
{
Console.WriteLine("Addition");
ReadInput();
int sum = num1 + num2;
Console.WriteLine("The sum is " + sum);
}
```
Contrary to 3dd's opinion, you should not call Addition method in the ReadInput method, because the ReadInput method, as its name suggests, is only responsible for reading inputs, Also, the Addition method's only task is to perform addition and send the result to the caller so that the caller can use as it wants. and if you call Addition inside ReadInput, you have violated the SRP principle.,
You can optimize your code as follows. Consider the output for the ReadtInput method and the input and output for the Addition method.
you can use tuples or create a separate model, I will write both for you.
with Tuple :
public class HelloWorld
{
public (int number1, int number2) ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
return (num1, num2);
}
public int Addition(int num1, int num2)
{
Console.WriteLine("Addition");
int sum = num1 + num2;
return sum;
}
}
How to use :
internal class Program
{
static void Main(string[] args)
{
HelloWorld helloWorld = new HelloWorld();
var result = helloWorld.ReadInput();
var sumResult = helloWorld.Addition(result.number1, result.number2);
Console.WriteLine("The sum is " + sumResult);
}
}
If you don't want to use tuple, you create a model like below, the changes are as follows :
public class ReadInputModel
{
public int Number1 { get; set; }
public int Number2 { get; set; }
}
And the ReadInput method changes as follows
public ReadInputModel ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
return new ReadInputModel
{
Number1 = num1,
Number2 = num2
};
}
Just pay attention to this point, I only optimized you Code, but still the principles of creating and designing methods are not well followed,for example, you should not do Console.WriteLine in the ReadInput method and its only task should be to read information ,and other things which I think cannot be explained here, it is better to study the principles of Solid well.
I recommend reading these articles:
Solid
SOLID Principles In C#
Csharp best practices dangers of violating solid principles in csharp
public void ReadInput()
{
Console.WriteLine("Insert a first number:");
var num1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Insert a second number");
var num2 = Convert.ToInt32(Console.ReadLine());
Addition(num1 , num2);
}
public void Addition(int num1, int num2)
{
Console.WriteLine("Addition");
int sum = num1 + num2;
Console.WriteLine("The sum is " + sum);
}

Problem with variables while trying to make a c# library(.dll)

I want to make a library that sums 2 numbers(a and b) and then stores the value into a result variable inside a library(.dll).
I tried this:
public static void Sum(int number1, int number2, int result)
{
result = number1 + number2;
}
but I can't make it so that in a program that uses this library, you can get the value of the result value that this function calculates and that's what I couldn't figure out for the past days. If you need any more info I will gladly provide it to you! Hope someone can help me!
In your case you do not return any result, consider using some of the following:
public static void Main()
{
var sumRes = SumResut(1, 2);
Console.WriteLine($"SumResult = {sumRes}");
OutSum(1, 2, out int outRes);
Console.WriteLine($"OutSum = {outRes}");
int refRes = 0;
RefSum(1, 2, ref refRes);
Console.WriteLine($"RefSum = {refRes}");
}
public static int SumResut(int number1, int number2)
{
return number1 + number2;
}
public static void OutSum(int number1, int number2, out int result)
{
result = number1 + number2;
}
public static void RefSum(int number1, int number2, ref int result)
{
result = number1 + number2;
}

C# Compound Interest Calculator Using a Loop (Error CS0103)

I want to create a Compound Interest Calculator in C# using two classes in different namespaces but can't for the life of me figure out why I keep getting errors.
PSA I am a beginner, I know this code probably looks awful, but please be kind.
Here is CompoundTest.cs
namespace CompoundTest
{
class Program
{
static void Main(string[] args)
{
CompoundClass newprogram = new CompoundClass();
Console.Write("\nPlease enter the initial balance for your account: ");
double balance = Convert.ToDouble(Console.ReadLine());
Console.Write("\nPlease enter the annual interest rate: ");
double interestRate = Convert.ToDouble(Console.ReadLine()) / 100;
Console.Write("\nHow many years will you acrue interest? ");
double annualAmount = Convert.ToDouble(Console.ReadLine());
Console.WriteLine($"Your balance after {annualAmount} years is {accountBalance:C}");
Console.ReadLine();
}
}
}
And here is Compound.cs
using System;
namespace Compound
{
public class CompoundClass
{
private double balance;
public int value { get; private set; }
public CompoundClass()
{
Balance = value;
}
public double Balance
{
get
{
return balance;
}
private set
{
if (value > 0)
{
balance = value;
}
}
}
public void Rate(double interestRate)
{
interestRate = value / 100;
}
public void Years(double annualAmount)
{
annualAmount = value * 12;
}
public void addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
accountBalance = balance * Math.Pow(1 + interestRate / annualAmount, annualAmount * i);
}
}
}
}
I get the error:
CS0103 C# The name '..' does not exist in the current context - in the public void addMethod(double accountBalance) method
You are not storing any data on the CompoundClass, the method
public void Rate(double interestRate)
{
interestRate = value / 100;
}
only operates on the input parameter interestrate inside the functions scope, after that the result of the calculation is lost
If you want to reuse a variable on the entire lifetime of the CompoundClass, then define it as a member variable like:
private double _interestRate
and change your function to
public void Rate()
{
_interestRate = value / 100;
}
and for the annualAmount as well
private double _annualAmount;
public void Years()
{
_annualAmount = value * 12;
}
and your calculation to
public double addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
accountBalance = balance * Math.Pow(1 + _interestRate / _annualAmount, _annualAmount * i);
}
return accountBalance;
}
There is more then one thing wrong with this code. And I am honestly not sure if I even got anything close to your problem yet.
using System;
namespace Compound
{
public class CompoundClass
{
private double balance;
public int value { get; private set; }
public CompoundClass()
{
//Balance with a big B is nowhere in context
Balance = value;
}
public double Balance
{
get
{
return balance;
}
private set
{
if (value > 0)
{
balance = value;
}
}
}
//As remarked by somebody else, this function does nothing. Without return or out parameter, interest rate will stay at nothing.
public void Rate(double interestRate)
{
interestRate = value / 100;
}
//The naming of this variable is bad. Did you mean "Amoung of Months"?
//Also as someone else pointed out, you do not return or otherwise persist this value
public void Years(double annualAmount)
{
annualAmount = value * 12;
}
//Method does not return anything.
//accountBalance is a local value and will not persist
public void addMethod(double accountBalance)
{
for (int i = 1; i < annualAmount + 1; i++)
{
//Avoid putting that much stuff into 1 line. It really messes with your ability to debug
//1-2 operations + 1 assignment to a temporary variable per line
//Anything more and you will have serious issues debugging this
accountBalance = balance * Math.Pow(1 + interestRate / annualAmount, annualAmount * i);
}
}
}
}
Generally the variables this works with should be either purely parameters (wich means it should be a static class with static functions) or mostly class variables. You have both things mixed all over the place.

How to call a function from another class to main class

I created another class (calculations) and created a function in it which checks if a number is even or odd. I want to call this function in my program class so it can check if variable (result) is even or odd.
I tried to call the method like: CheckEvenOrOdd(result).
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number2 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
// i tried this here but it doesn't work: CheckEvenOrOdd(result)
}
}
class Calculations
{
public static void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}
Because your method is in a different class, you're going to have to make it static and then call it by class name first then method name. If it's not static you're going to have to instantiate a new instance of that class before being able to access any of its methods.
(btw you're multiplying number2 by number2, changed it for you as well in the codes provided below hehe)
Static:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public static class Calculations
{
public static void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}
Not Static:
class Program
{
static void Main(string[] args)
{
int number1;
int number2;
int result;
Console.Write("Enter a number: ");
number1 = int.Parse(Console.ReadLine());
Console.Write("Enter a second number: ");
number2 = int.Parse(Console.ReadLine());
result = number1 * number2;
Console.WriteLine($"The total is: {result} ");
Console.WriteLine("AND");
Calculations calc = new Calculations();
calc.CheckEvenOrOdd(result);
Console.ReadLine();
}
}
public class Calculations
{
public void CheckEvenOrOdd(int numb)
{
if (numb % 2 == 0)
{
Console.WriteLine("The number is even");
}
else
{
Console.WriteLine("The number is odd ");
}
}
}

METHOD concept program in c# is not working

using System;
class Methodcalling
{
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args)
{
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
int result = m.Values(a, b);
}
}
ERROR:'Methodcalling.Values(int, int)': not all code paths return a value
In this way its showing error in VISUAL STUDIO 2013.
This error is because you have declared the function to return an int, but your function does not return anything.
Have a look at this link here for a reference on the function declaration in c#.
For a relief from the error, try adding return 0; to the end of the function.
public int Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
return 0; // Return zero to the calling function.
}
Now you could call this function like this to capture the return value.
int TheReturnValue = Values(num1 , num2); //You will get 0 as value for TheReturnValue variable.
or change the int to void as in public void Values(int num1, int num2) if you don't want to return any values.
here is the usage:
public void Values(int num1, int num2)
{
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
and you could call the function(void Return Type) like this:
m.Values(a, b); //without assigning it to a variable
Since you are only writing to console using this function, void datatype would be the better option.
I hope this helps.
You have to return an int value from the method as the method's signature defines a return type of int, and you are also calling
int result = m.Values(a, b);
which suggest that the method would return an integer but you have no return statement in your method.
You can modify the method like this if you don't want any integer to be returned.
using System;
class Methodcalling {
public void Values(int num1, int num2) {
if (num1 > num2)
{
Console.WriteLine("num2 is large ");
}
else
{
Console.WriteLine("num1 is big");
}
}
static void Main(string[] args) {
int a, b;
Methodcalling m = new Methodcalling();
Console.WriteLine("enter a no.:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("enter a no.:");
b = Convert.ToInt32(Console.ReadLine());
m.Values(a, b);
}
}

Categories

Resources