TGViewer
Библиотека шарписта | C#, F#, .NET, ASP.NET Библиотека шарписта | C#, F#, .NET, ASP.NET @csharpproglib · 21.7K subscribers
Post #6813 3.35K
🧑‍💻 Юнит-тестирование F# с xUnit

Рассмотрим, как настроить юнит-тестирование 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
  • ❤ 5
  • 🤔 1
More from @csharpproglib
  1. Sep 25, 2026🔐 NuGet: Microsoft меняет сертификат подписи С 23 сентября Microsoft использует новый сер…
  2. Sep 24, 2026🤩 Как поймать зависший .NET-сервис Приложение начинает тормозить, запросы зависают, а в л…
  3. Sep 23, 2026⚙️ yield return не бесплатный Итераторы выглядят просто, но работают иначе: IEnumerable<in…
  4. Sep 22, 2026💡 Replace, Regex или StringBuilder? Для замены текста в C# есть несколько инструментов. И…
  5. Sep 21, 2026⚙️ Настоящие атомарные операции Если Volatile решает проблему видимости, то Interlocked ре…
  6. Sep 20, 2026💪 Разминка перед трудовыми буднями Что произойдёт? ❤️ — список станет [1, 3] 🔥 — Invalid…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →