Рассмотрим, как настроить юнит-тестирование F#-библиотеки с помощью
xUnit и dotnet test.Для чистоты разделим библиотеку и тесты на два отдельных проекта внутри одного solution:
/unit-testing-with-fsharp
unit-testing-with-fsharp.sln
/MathService ← бизнес-логика
/MathService.Tests ← тесты
Создаём скелет проекта:
mkdir unit-testing-with-fsharp && cd unit-testing-with-fsharp
dotnet new sln
mkdir MathService && cd MathService
dotnet new classlib -lang "F#"
cd ..
dotnet sln add ./MathService/MathService.fsproj
Наша тестируемая функция:
module MyMath =
let private isOdd x = x % 2 <> 0
let private square x = x * x
let squaresOfOdds xs =
xs
|> Seq.filter isOdd
|> Seq.map square
Цель функции — принять последовательность целых чисел и вернуть квадраты всех нечётных элементов.
Настраиваем тестовый проект:
mkdir MathService.Tests && cd MathService.Tests
dotnet new xunit -lang "F#"
dotnet reference add ../MathService/MathService.fsproj
cd ..
dotnet sln add ./MathService.Tests/MathService.Tests.fsproj
Команда
dotnet reference add доступна в .NET 10+. На более ранних SDK используйте dotnet add reference.Тесты:
module MathService.Tests
open Xunit
[<Fact>]
let ``Sequence of Evens returns empty collection`` () =
let expected = Seq.empty<int>
let actual = MyMath.squaresOfOdds [2; 4; 6; 8; 10]
Assert.Equal<Collections.Generic.IEnumerable<int>>(expected, actual)
[<Fact>]
let ``Sequences of Ones and Evens returns Ones`` () =
let expected = [1; 1; 1; 1]
let actual = MyMath.squaresOfOdds [2; 1; 4; 1; 6; 1; 8; 1; 10]
Assert.Equal<Collections.Generic.IEnumerable<int>>(expected, actual)
[<Fact>]
let ``SquaresOfOdds works`` () =
let expected = [1; 9; 25; 49; 81]
let actual = MyMath.squaresOfOdds [1; 2; 3; 4; 5; 6; 7; 8; 9; 10]
Assert.Equal(expected, actual)
➡️ Оригинальная документация
📍 Навигация: Вакансии • Задачи • Собесы
🐸 Библиотека шарписта
#sharp_view