import XCTest
@testable import YourAppModule
class Calculator {
func add(_ a: Int, _ b: Int) -> Int {
return a + b
}
func subtract(_ a: Int, _ b: Int) -> Int {
return a - b
}
}
class CalculatorTests: XCTestCase {
var calculator: Calculator!
override func setUp() {
super.setUp()
calculator = Calculator()
}
override func tearDown() {
calculator = nil
super.tearDown()
}
func testAddition() {
let result = calculator.add(2, 3)
XCTAssertEqual(result, 5, "Addition should return the sum of two numbers")
}
func testSubtraction() {
let result = calculator.subtract(5, 3)
XCTAssertEqual(result, 2, "Subtraction should return the difference of two numbers")
}
}
This solution creates a simple Calculator class with two methods: add and subtract. Each method returns the correct arithmetic result.
The CalculatorTests class inherits from XCTestCase. It uses setUp() to create a new calculator instance before each test and tearDown() to clean up after tests.
Two test methods check the calculator's behavior: testAddition verifies that adding 2 and 3 returns 5, and testSubtraction verifies that subtracting 3 from 5 returns 2. The XCTAssertEqual function compares expected and actual results, showing a message if the test fails.
This approach helps ensure the calculator works correctly and teaches how to write basic unit tests with XCTest.