Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Волков Кирилл #236

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
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
Original file line number Diff line number Diff line change
@@ -1,34 +1,9 @@
using System;
using System.Text.RegularExpressions;
using FluentAssertions;
using NUnit.Framework;

namespace HomeExercises
{
public class NumberValidatorTests
{
[Test]
public void Test()
{
Assert.Throws<ArgumentException>(() => new NumberValidator(-1, 2, true));
Assert.DoesNotThrow(() => new NumberValidator(1, 0, true));
Assert.Throws<ArgumentException>(() => new NumberValidator(-1, 2, false));
Assert.DoesNotThrow(() => new NumberValidator(1, 0, true));

Assert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
Assert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0"));
Assert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("00.00"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-0.00"));
Assert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+0.00"));
Assert.IsTrue(new NumberValidator(4, 2, true).IsValidNumber("+1.23"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+1.23"));
Assert.IsFalse(new NumberValidator(17, 2, true).IsValidNumber("0.000"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-1.23"));
Assert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("a.sd"));
}
}
// тесты в Tests/NumberValues_Should

public class NumberValidator
{
Expand Down
56 changes: 3 additions & 53 deletions cs/HomeExercises/ObjectComparison.cs
Original file line number Diff line number Diff line change
@@ -1,57 +1,7 @@
using FluentAssertions;
using NUnit.Framework;

namespace HomeExercises
namespace HomeExercises
{
public class ObjectComparison
{
[Test]
[Description("Проверка текущего царя")]
[Category("ToRefactor")]
public void CheckCurrentTsar()
{
var actualTsar = TsarRegistry.GetCurrentTsar();

var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));

// Перепишите код на использование Fluent Assertions.
Assert.AreEqual(actualTsar.Name, expectedTsar.Name);
Assert.AreEqual(actualTsar.Age, expectedTsar.Age);
Assert.AreEqual(actualTsar.Height, expectedTsar.Height);
Assert.AreEqual(actualTsar.Weight, expectedTsar.Weight);

Assert.AreEqual(expectedTsar.Parent!.Name, actualTsar.Parent!.Name);
Assert.AreEqual(expectedTsar.Parent.Age, actualTsar.Parent.Age);
Assert.AreEqual(expectedTsar.Parent.Height, actualTsar.Parent.Height);
Assert.AreEqual(expectedTsar.Parent.Parent, actualTsar.Parent.Parent);
}

[Test]
[Description("Альтернативное решение. Какие у него недостатки?")]
public void CheckCurrentTsar_WithCustomEquality()
{
var actualTsar = TsarRegistry.GetCurrentTsar();
var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));

// Какие недостатки у такого подхода?
Assert.True(AreEqual(actualTsar, expectedTsar));
}

private bool AreEqual(Person? actual, Person? expected)
{
if (actual == expected) return true;
if (actual == null || expected == null) return false;
return
actual.Name == expected.Name
&& actual.Age == expected.Age
&& actual.Height == expected.Height
&& actual.Weight == expected.Weight
&& AreEqual(actual.Parent, expected.Parent);
}
}

// Тесты в Tests/ObjectComparison_Should

public class TsarRegistry
{
public static Person GetCurrentTsar()
Expand Down
133 changes: 133 additions & 0 deletions cs/HomeExercises/Tests/NumberValidator_Should.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
using System;
using System.Collections;
using FluentAssertions;
using NUnit.Framework;

namespace HomeExercises.Tests
{
public class NumberValidator_Should
{
#region ConstructorTestsSources

private static IEnumerable IncorrectConstructorParamsTests()
{
yield return new TestCaseData(-1, 2, true, "precision must be a positive number")
.SetName("Constructor_ThrowsArgumentExceptionOnNegativePrecision");
yield return new TestCaseData(0, 2, true, "precision must be a positive number")
.SetName("Constructor_ThrowsArgumentExceptionOnZeroPrecision");
yield return new TestCaseData(1, 2, true, "precision must be a non-negative number less or equal than precision")
.SetName("Constructor_ThrowsArgumentExceptionOnPrecisionLessThanScale");
yield return new TestCaseData(1, 1, true, "precision must be a non-negative number less or equal than precision")
.SetName("Constructor_ThrowsArgumentExceptionSamePrecisionAndScale");
yield return new TestCaseData(1, -1, true, "precision must be a non-negative number less or equal than precision")
.SetName("Constructor_ThrowsArgumentExceptionOnNegativeScale");
}

private static IEnumerable CorrectConstructorParamsTests()
{
yield return new TestCaseData(2, 1, true)
.SetName("Constructor_WorksWhenPrecisionIsNonNegativeAndGreaterThanScale");
yield return new TestCaseData(2, 1, false)
.SetName("Constructor_WorksWhenPrecisionIsNonNegativeAndGreaterThanScale");
}

#endregion

#region IsValidNumberTestsSources

private static IEnumerable IsValidNumberPrecisionTests()
{
yield return new TestCaseData(3, 2, true, "00.00")
.SetName("IsValidNumber_ReturnsFalse_WhenSumOfIntPartAndFracPartIsGreaterThanPrecision")
.Returns(false);
yield return new TestCaseData(3, 2, true, "-0.00")
.SetName("IsValidNumber_ReturnsFalse_WhenSignWithFracAndIntPartsIsGreaterThanPrecision")
.Returns(false);
yield return new TestCaseData(3, 2, true, "+0.00")
.SetName("IsValidNumber_ReturnsFalse_WhenSignWithFracAndIntPartsIsGreaterThanPrecision")
.Returns(false);

yield return new TestCaseData(17, 2, true, "0.0")
.SetName("IsValidNumber_ReturnsTrue_WhenSumOfIntPartAndFracPartIsNotGreaterThanPrecision")
.Returns(true);
yield return new TestCaseData(17, 2, true, "0")
.SetName("IsValidNumber_ReturnsTrue_WhenIntPartIsNotGreaterThanPrecision")
.Returns(true);
yield return new TestCaseData(17, 2, true, "+0.0")
.SetName("IsValidNumber_ReturnsTrue_WhenSumOfIntPartAndFracPartIsNotGreaterThanPrecision")
.Returns(true);
}

private static IEnumerable IsValidNumberScaleTests()
{
yield return new TestCaseData(17, 2, true, "0.111")
.SetName("IsValidNumber_ReturnsFalse_WhenFracPartIsGreaterThanScale")
.Returns(false);

yield return new TestCaseData(17, 2, true, "0.11")
.SetName("IsValidNumber_ReturnsTrue_WhenFracPartIsNotGreaterThanScale")
.Returns(true);
}

private static IEnumerable IsValidNumberSignTests()
{
yield return new TestCaseData(17, 2, true, "-0.11")
.SetName("IsValidNumber_ReturnsFalse_WhenSignIsNegativeWithOnlyPositive")
.Returns(false);

yield return new TestCaseData(17, 2, true, "+0.11")
.SetName("IsValidNumber_ReturnsTrue_WhenSignIsPositiveWithOnlyPositive")
.Returns(true);
yield return new TestCaseData(17, 2, false, "+0.11")
.SetName("IsValidNumber_ReturnsTrue_WhenSignIsPositiveWithoutOnlyPositive")
.Returns(true);
yield return new TestCaseData(17, 2, false, "-0.11")
.SetName("IsValidNumber_ReturnsTrue_WhenSignIsNegativeWithoutOnlyPositive")
.Returns(true);
}

private static IEnumerable IsValidNumberValueTests()
{
yield return new TestCaseData(17, 2, true, null)
.SetName("IsValidNumber_ReturnsFalse_WhenNullIsGiven")
.Returns(false);
yield return new TestCaseData(17, 2, true, "")
.SetName("IsValidNumber_ReturnsFalse_WhenEmptyStringIsGiven")
.Returns(false);
yield return new TestCaseData(17, 2, true, "a.a")
.SetName("IsValidNumber_ReturnsFalse_WhenNonDigitStringIsGiven")
.Returns(false);
}

#endregion

[TestCaseSource(nameof(IncorrectConstructorParamsTests))]
public void FailsWithIncorrectConstructorArguments(int precision, int scale, bool onlyPositive, string message)
{
new Func<NumberValidator>(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.ThrowExactly<ArgumentException>()
.Where(e => e.Message.Equals(message, StringComparison.OrdinalIgnoreCase));
}

[TestCaseSource(nameof(CorrectConstructorParamsTests))]
public void InitsWithCorrectConstructorArguments(int precision, int scale, bool onlyPositive)
{
new Func<NumberValidator>(() => new NumberValidator(precision, scale, onlyPositive))
.Should()
.NotThrow();
}

[
TestCaseSource(nameof(IsValidNumberPrecisionTests)),
TestCaseSource(nameof(IsValidNumberScaleTests)),
TestCaseSource(nameof(IsValidNumberSignTests)),
TestCaseSource(nameof(IsValidNumberValueTests)),
]
public bool IsValidNumber(int precision, int scale, bool onlyPositive, string value)
{
return new Func<NumberValidator>(() => new NumberValidator(precision, scale, onlyPositive))()
.IsValidNumber(value);
}
}
}
64 changes: 64 additions & 0 deletions cs/HomeExercises/Tests/ObjectComparsion_Should.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
using FluentAssertions;
using FluentAssertions.Equivalency;
using NUnit.Framework;

namespace HomeExercises.Tests
{
public class ObjectComparison_Should
{
private Person actualTsar;
private Person expectedTsar;

[SetUp]
public void SetUp()
{
actualTsar = TsarRegistry.GetCurrentTsar();
expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,
new Person("Vasili III of Russia", 28, 170, 60, null));
}

[Test]
[Description("Проверка текущего царя")]
[Category("ToRefactor")]
public void CheckCurrentTsar()
{
actualTsar.Should().BeEquivalentTo(expectedTsar, options =>
options
.IncludingFields()
.Excluding(memberInfo =>
memberInfo.SelectedMemberInfo.Name == nameof(Person.Id)
&& memberInfo.SelectedMemberInfo.DeclaringType == typeof(Person)));
}

[Test]
[Description("Альтернативное решение. Какие у него недостатки?")]
public void CheckCurrentTsar_WithCustomEquality()
{
Assert.True(AreEqual(actualTsar, expectedTsar));

// Какие недостатки у такого подхода?
// 1. При большой родословной будут проверяться все предки. И, при наличии расхождения у родителей, нам будет сложно понять в каком объекте произошло падение теста
// 2. Из названия теста непонятно, что именно значит CustomEquality и какое у него поведение
// 3. Не показывается информация, на каком именно объекте тест упал, что усложняет разработку
// 4. При расширении класса Person нужно будет дописывать AreEqual, а в FluentAssertions достаточно указать IncludingFields в конфигурации и все поля автоматически будут сравниваться
// 5. Повышается читабельность и тесты проще писать
// 7. Не инкапсулирована функциональность сравнения внутри класса

// Улучшайзинги
// 1. Также я вынес инициализацию объектов в метод SetUp, помеченный соответствующим атрибутом
// 2. Для структурированности проекта вынес тесты в папку Tests
}

private bool AreEqual(Person? actual, Person? expected)
{
if (actual == expected) return true;
if (actual == null || expected == null) return false;
return
actual.Name == expected.Name
&& actual.Age == expected.Age
&& actual.Height == expected.Height
&& actual.Weight == expected.Weight
&& AreEqual(actual.Parent, expected.Parent);
}
}
}