Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions HW5/HW5.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyNUnit", "MyNUnit\MyNUnit.csproj", "{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyNUnit.Tests", "MyNUnit.Tests\MyNUnit.Tests.csproj", "{56F3864E-325F-4124-BC63-0AFE972FFAE1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|x64.ActiveCfg = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|x64.Build.0 = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|x86.ActiveCfg = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Debug|x86.Build.0 = Debug|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|Any CPU.Build.0 = Release|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|x64.ActiveCfg = Release|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|x64.Build.0 = Release|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|x86.ActiveCfg = Release|Any CPU
{FEC922AC-BF64-4C53-AE57-27F93A60EA2B}.Release|x86.Build.0 = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|x64.ActiveCfg = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|x64.Build.0 = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|x86.ActiveCfg = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Debug|x86.Build.0 = Debug|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|Any CPU.Build.0 = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|x64.ActiveCfg = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|x64.Build.0 = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|x86.ActiveCfg = Release|Any CPU
{56F3864E-325F-4124-BC63-0AFE972FFAE1}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal
46 changes: 46 additions & 0 deletions HW5/MyNUnit.Tests/Calculator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
// <copyright file="Calculator.cs" company="khusainovilas">
// Copyright (c) khusainovilas. All rights reserved.
// </copyright>

namespace MyNUnit.Tests;

/// <summary>
/// Simple calculator class.
/// </summary>
public static class Calculator
{
/// <summary>
/// Adds two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The sum of a and b.</returns>
public static int Add(int a, int b) => a + b;

/// <summary>
/// Subtracts second number from first.
/// </summary>
/// <param name="a">The number to subtract from.</param>
/// <param name="b">The number to subtract.</param>
/// <returns>The result of a minus b.</returns>
public static int Subtract(int a, int b) => a - b;

/// <summary>
/// Multiplies two numbers.
/// </summary>
/// <param name="a">The first number.</param>
/// <param name="b">The second number.</param>
/// <returns>The product of a and b.</returns>
public static int Multiply(int a, int b) => a * b;

/// <summary>
/// Divides first number by second.
/// </summary>
/// <param name="a">The dividend.</param>
/// <param name="b">The divisor.</param>
/// <returns>The result of a divided by b.</returns>
public static int Divide(int a, int b)
{
return b == 0 ? throw new DivideByZeroException() : a / b;
}
}
75 changes: 75 additions & 0 deletions HW5/MyNUnit.Tests/CalculatorTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// <copyright file="CalculatorTests.cs" company="khusainovilas">
// Copyright (c) khusainovilas. All rights reserved.
// </copyright>

namespace MyNUnit.Tests;

using System;

/// <summary>
/// Tests for the <see cref="Calculator"/> class using MyNUnit.
/// </summary>
public class CalculatorTests
{
/// <summary>
/// Checks the addition of two numbers.
/// </summary>
[Test]
public void Calculator_Add_ShouldReturnSum()
{
var result = Calculator.Add(2, 3);
if (result != 5)
{
throw new InvalidOperationException($"Expected 5, but got {result}");
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если уж Вы заморочились и написали настоящие тесты, то можно было дополнительно заморочиться и написать свой Assert.

}

/// <summary>
/// Checks the subtraction of two numbers.
/// </summary>
[Test]
public void Calculator_Subtract_ShouldReturnDifference()
{
var result = Calculator.Subtract(10, 4);
if (result != 6)
{
throw new InvalidOperationException($"Expected 6, but got {result}");
}
}

/// <summary>
/// Checks division by zero (should throw an exception).
/// </summary>
[Test(Expected = typeof(DivideByZeroException))]
public void Calculator_Divide_ByZero_ShouldThrow()
{
Calculator.Divide(10, 0);
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

И можно более активно использовать =>


/// <summary>
/// Ignored test.
/// </summary>
[Test]
[Ignore("Example of a ignored test")]
public void Calculator_Multiply_ShouldBeIgnored()
{
var result = Calculator.Multiply(3, 4);
if (result != 12)
{
throw new InvalidOperationException($"Expected 12, but got {result}");
}
}

/// <summary>
/// A special test that intentionally crashes.
/// </summary>
[Test]
public void Calculator_FailedTest_ShouldFail()
{
var result = Calculator.Add(1, 1);
if (result != 3)
{
throw new InvalidOperationException("This test is supposed to fail");
}
}
}
87 changes: 87 additions & 0 deletions HW5/MyNUnit.Tests/MyNUnit.Tests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
// <copyright file="MyNUnit.Tests.cs" company="khusainovilas">
// Copyright (c) khusainovilas. All rights reserved.
// </copyright>

namespace MyNUnit.Tests;

using System;
using System.Linq;
using NUnitTest = NUnit.Framework.TestAttribute;

/// <summary>
/// Tests which check the correct behavior MyNUnit.
/// </summary>
public class MyNUnitRunnerTests
{
private static readonly Type CalculatorTestsType = typeof(CalculatorTests);

/// <summary>
/// Test MyNUnit runs all tests.
/// </summary>
[NUnitTest]
public void MyNUnitRunnerTests_CalculatorTests_Run_ShouldReturnCorrectStatistics()
{
var results = TestRunner.Run([CalculatorTestsType]);

var passedCount = results.Count(r => r.Status == TestStatus.Passed);
var failedCount = results.Count(r => r.Status == TestStatus.Failed);
var ignoredCount = results.Count(r => r.Status == TestStatus.Ignored);

Assert.Multiple(() =>
{
Assert.That(passedCount, Is.EqualTo(3), "Passed tests count is incorrect");
Assert.That(failedCount, Is.EqualTo(1), "Failed tests count is incorrect");
Assert.That(ignoredCount, Is.EqualTo(1), "Ignored tests count is incorrect");
});
}

/// <summary>
/// Test MyNUnit with an expected exception.
/// </summary>
[NUnitTest]
public void MyNUnitRunnerTests_CalculatorTests_ExpectedException_ShouldPass()
{
var results = TestRunner.Run([CalculatorTestsType]);

var testResult = results.First(
r => r.TestName.EndsWith("Calculator_Divide_ByZero_ShouldThrow"));

Assert.That(testResult.Status, Is.EqualTo(TestStatus.Passed));
}

/// <summary>
/// Test MyNUnit ignored tests.
/// </summary>
[NUnitTest]
public void MyNUnitRunnerTests_CalculatorTests_IgnoredTest_ShouldBeIgnored()
{
var results = TestRunner.Run([CalculatorTestsType]);

var testResult = results.First(
r => r.TestName.EndsWith("Calculator_Multiply_ShouldBeIgnored"));

Assert.Multiple(() =>
{
Assert.That(testResult.Status, Is.EqualTo(TestStatus.Ignored));
Assert.That(testResult.Message, Is.Not.Empty);
});
}

/// <summary>
/// Test MyNUnit a failing test.
/// </summary>
[NUnitTest]
public void MyNUnitRunnerTests_CalculatorTests_FailedTest_ShouldFail()
{
var results = TestRunner.Run([CalculatorTestsType]);

var testResult = results.First(
r => r.TestName.EndsWith("Calculator_FailedTest_ShouldFail"));

Assert.Multiple(() =>
{
Assert.That(testResult.Status, Is.EqualTo(TestStatus.Failed));
Assert.That(testResult.Exception, Is.Not.Null);
});
}
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Надо ещё проверить на ситуацию, когда исключение ожидалось, но не брошено, на то, что вызываются Before/After и т.д., и на исключения в них.

39 changes: 39 additions & 0 deletions HW5/MyNUnit.Tests/MyNUnit.Tests.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<LangVersion>latest</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageReference Include="NUnit" Version="4.2.2" />
<PackageReference Include="NUnit.Analyzers" Version="4.4.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.6.0" />
</ItemGroup>

<ItemGroup>
<Using Include="NUnit.Framework" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="StyleCop.Analyzers" Version="1.1.118">

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

StyleCop староват, надо 1.2-beta. Иначе он нового C# не знает

<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<AdditionalFiles Include="stylecop.json" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\MyNUnit\MyNUnit.csproj" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions HW5/MyNUnit.Tests/stylecop.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"settings": {
"documentationRules": {
"companyName": "khusainovilas",
"copyrightText": "Copyright (c) {companyName}. All rights reserved."
}
}
}
70 changes: 70 additions & 0 deletions HW5/MyNUnit/Attributes.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
// <copyright file="Attributes.cs" company="khusainovilas">
// Copyright (c) khusainovilas. All rights reserved.
// </copyright>

namespace MyNUnit;

/// <summary>
/// Marks the method as a test.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class TestAttribute : Attribute
{
/// <summary>
/// Gets or sets the expected exception type.
/// </summary>
public Type? Expected { get; set; }
}

/// <summary>
/// Skip the test with an indication of the reason.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class IgnoreAttribute : Attribute
{
/// <summary>
/// Initializes a new instance of the <see cref="IgnoreAttribute"/> class.
/// </summary>
/// <param name="reason">The reason for ignoring the test.</param>
public IgnoreAttribute(string reason)
{
this.Reason = reason ?? throw new ArgumentNullException(nameof(reason));
}

/// <summary>
/// Gets the reason why the test is ignored.
/// </summary>
public string Reason { get; }
}

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ignore просили просто как строковое свойство у атрибута Test, но окей, так тоже сойдёт, можно не править


/// <summary>
/// Runs once before all tests in the class.
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class BeforeClassAttribute : Attribute
{
}

/// <summary>
/// Runs once after all the tests in the class.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AfterClassAttribute : Attribute
{
}

/// <summary>
/// Runs before each test.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class BeforeAttribute : Attribute
{
}

/// <summary>
/// Runs after each test.
/// </summary>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
public class AfterAttribute : Attribute

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Вообще, в C# есть правило "Один класс — один файл", лучше было атрибуты сложить в отдельную папку, по одному в файле. А ещё лучше атрибуты вынести в отдельную сборку, потому что иначе всем, кто пишет тесты, надо будет линковаться со всем раннером, тогда как им нужны только атрибуты.

{
}
Loading