0 day streak
csharp / beginner
Snippet

Manual Logic Result Check

Testing is the practice of verifying that your code behaves as expected. In this beginner example, we manually check a method's return value and throw an error if the logic is incorrect.

snippet.cs
csharp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
using System;
public class Calculator {
public int Add(int a, int b) => a + b;
}
public class MiniTest {
public void Run() {
var calc = new Calculator();
if (calc.Add(5, 5) != 10) {
throw new Exception("Math logic failed!");
}
Console.WriteLine("Test passed.");
}
}
Breakdown
1
if (calc.Add(5, 5) != 10)
Compares the actual result of the method with the expected value.
2
throw new Exception(...)
Interrupts the program and reports a failure if the test condition is not met.