This example showcases the basic operations of a calculator, such as addition, subtraction, multiplication, and division, as well as memory operations. The unit tests validate these operations using MSTest, ensuring accuracy and exception handling (e.g., division by zero).
namespace CalculatorApp
{
public class Calculator
{
private double? _memory;
public void MemoryStore(double value)
{
_memory = value;
}
public double? MemoryRecall()
{
return _memory;
}
public void MemoryClear()
{
_memory = null;
}
public double Add(double a, double b)
{
return a + b;
}
public double Subtract(double a, double b)
{
return a - b;
}
public double Multiply(double a, double b)
{
return a * b;
}
public double Divide(double a, double b)
{
if (b == 0)
throw new DivideByZeroException();
return (double)a / b;
}
}
}
The following unit tests ensure that each method of our calculator behaves as expected:
namespace CalculatorApp.Tests.MSTest
{
[TestClass]
public class CalculatorTests
{
private Calculator _calculator;
// Constructor where we initialize _calculator
public CalculatorTests()
{
_calculator = new Calculator();
}
[TestMethod]
public void TestMemoryFunctions()
{
// Store 5 in memory
_calculator.MemoryStore(5);
// Add 5 (from memory) and 3
var memoryValue = _calculator.MemoryRecall();
Assert.IsNotNull(memoryValue, "Memory value is null."); // Ensure memoryValue is not null
Assert.AreEqual(5, memoryValue); // Ensure value from memory is correct
var result = _calculator.Add(memoryValue.Value, 3);
Assert.AreEqual(8, result);
// Clear memory and ensure it's null
_calculator.MemoryClear();
Assert.IsNull(_calculator.MemoryRecall());
}
[TestMethod]
[DataRow(1, 1, 2)]
[DataRow(-1, -1, -2)]
[DataRow(100, 50, 150)]
[DataRow(0, 0, 0)]
public void TestAddWithMultipleData(int a, int b, int expected)
{
var result = _calculator.Add(a, b);
Assert.AreEqual(expected, result);
}
[TestMethod]
public void TestAdd()
{
var result = _calculator.Add(3.2, 5);
Assert.AreEqual(8.2, result);
}
[TestMethod]
public void TestSubtract()
{
var result = _calculator.Subtract(10, 5);
Assert.AreEqual(5, result);
}
[TestMethod]
public void TestMultiply()
{
var result = _calculator.Multiply(3, 5);
Assert.AreEqual(15, result);
}
[TestMethod]
public void TestDivide()
{
var result = _calculator.Divide(10, 5);
Assert.AreEqual(2, result);
}
[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public void TestDivideByZero()
{
_calculator.Divide(10, 0);
}
}
}
The tests cover basic arithmetic operations and demonstrate the power of unit testing to validate software functionality.
DataRow
attributes allows parameterized testing, enhancing test coverage with varying data points.