-
Notifications
You must be signed in to change notification settings - Fork 57
homework #40
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
base: master
Are you sure you want to change the base?
homework #40
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,5 +1,6 @@ | ||
| using NUnit.Framework; | ||
| using NUnit.Framework.Legacy; | ||
| using FluentAssertions; | ||
|
|
||
| namespace HomeExercise.Tasks.ObjectComparison; | ||
| public class ObjectComparison | ||
|
|
@@ -15,15 +16,16 @@ public void CheckCurrentTsar() | |
| new Person("Vasili III of Russia", 28, 170, 60, null)); | ||
|
|
||
| // Перепишите код на использование Fluent Assertions. | ||
| ClassicAssert.AreEqual(actualTsar.Name, expectedTsar.Name); | ||
| ClassicAssert.AreEqual(actualTsar.Age, expectedTsar.Age); | ||
| ClassicAssert.AreEqual(actualTsar.Height, expectedTsar.Height); | ||
| ClassicAssert.AreEqual(actualTsar.Weight, expectedTsar.Weight); | ||
|
|
||
| ClassicAssert.AreEqual(expectedTsar.Parent!.Name, actualTsar.Parent!.Name); | ||
| ClassicAssert.AreEqual(expectedTsar.Parent.Age, actualTsar.Parent.Age); | ||
| ClassicAssert.AreEqual(expectedTsar.Parent.Height, actualTsar.Parent.Height); | ||
| ClassicAssert.AreEqual(expectedTsar.Parent.Parent, actualTsar.Parent.Parent); | ||
| actualTsar | ||
| .Should() | ||
| .BeEquivalentTo(expectedTsar, options => options | ||
| .Excluding(info => info.Path.EndsWith(".Id") || info.Path == "Id") | ||
| ); | ||
| // Мы заменили 8 строчек тестов одной, так же если параметры класса Person поменяются в будущем нам не потребуется писать доп тесты, | ||
| // потому что FluentAssertions сравнивает все свойства, | ||
| // через Excluding мы исключили параметр id, чтобы тест не падал | ||
|
|
||
| } | ||
|
|
||
| [Test] | ||
|
|
@@ -34,7 +36,10 @@ public void CheckCurrentTsar_WithCustomEquality() | |
| var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70, | ||
| new Person("Vasili III of Russia", 28, 170, 60, null)); | ||
|
|
||
| // Какие недостатки у такого подхода? | ||
| // Какие недостатки у такого подхода? | ||
This comment was marked as resolved.
Sorry, something went wrong.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Будет рекурсия до бесконечности нужно добавить проверку что родитель не ссылается на царя нужно добавить что то по типу if (actual != actual.Parent) ; что ссылки разные |
||
|
|
||
| // Нам придется переписывать метод AreEqual каждый раз когда меняется класс Person, при падении мы получим только | ||
| // Что ожидалось True, а пришло False или наоборт, непонятно где ошибка | ||
| ClassicAssert.True(AreEqual(actualTsar, expectedTsar)); | ||
| } | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,31 +1,93 @@ | ||
| | ||
| using NUnit.Framework; | ||
| using NUnit.Framework.Legacy; | ||
| using FluentAssertions; | ||
|
|
||
| namespace HomeExercise.Tasks.NumberValidator; | ||
|
|
||
| [TestFixture] | ||
| public class NumberValidatorTests | ||
| { | ||
| [Test] | ||
| public void Test() | ||
| // тут решил добавить проверку на текст с ошибкой потому что иначе если первое верно срабатывала вторая проверка падала и | ||
| // получалось неверно и непонятно что упало | ||
| // например precision 1 и scale 1 и тест первый ниже проходит хотя должен не проходить | ||
|
|
||
| [TestCase(-1, 2, "precision must be a positive number", | ||
This comment was marked as resolved.
Sorry, something went wrong.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. разбил |
||
| TestName = "precision не может быть отрицательным")] | ||
| [TestCase(0, 2, "precision must be a positive number", | ||
| TestName = "precision не может быть равен 0")] | ||
| public void Constructor_WhenInvalidPrecisionProvided_ShouldThrow(int precision, int scale, string expectedMessage) | ||
| { | ||
| 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)); | ||
| Action act = () => new NumberValidator(precision, scale, true); | ||
| act | ||
| .Should() | ||
| .Throw<ArgumentException>() | ||
| .WithMessage(expectedMessage | ||
| ); | ||
| } | ||
|
|
||
|
|
||
| [TestCase(1, 2, "precision must be a non-negative number less or equal than precision", | ||
This comment was marked as resolved.
Sorry, something went wrong.
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Тут не понял, вроде везде на русском ток поля там на английском, а тут |
||
| TestName = "scale не может быть больше precision")] | ||
| [TestCase(1, 1, "precision must be a non-negative number less or equal than precision", | ||
| TestName = "scale не может быть равен precision")] | ||
| [TestCase(1, -1, "precision must be a non-negative number less or equal than precision", | ||
| TestName = "scale не может быть отрицательным")] | ||
| public void Constructor_WhenInvalidScaleProvided_ShouldThrow(int precision, int scale, string expectedMessage) | ||
| { | ||
| Action act = () => new NumberValidator(precision, scale, true); | ||
|
|
||
| act | ||
| .Should() | ||
| .Throw<ArgumentException>() | ||
| .WithMessage(expectedMessage | ||
| ); | ||
| } | ||
|
|
||
|
|
||
| [TestCase(1, 0, TestName = "scale может быть равен 0")] | ||
| [TestCase(7, 5, TestName = "Тест на создание объекта с правильными параметрами")] | ||
| public void Constructor_WhenValidParametersProvided_ShouldNotThrow(int precision, int scale) | ||
| { | ||
| Action act = () => new NumberValidator(precision, scale, true); | ||
|
|
||
| act | ||
| .Should() | ||
| .NotThrow<Exception>( | ||
| $"Не должно быть исключения при создании NumberValidator с precision={precision}, scale={scale}"); | ||
| } | ||
|
|
||
| [TestCase(6, 2, false, "-1.23", true, TestName = "Валидное отрицательное число")] | ||
| [TestCase(6, 2, true, "+1.23", true, TestName = "Валидное положительное число")] | ||
| [TestCase(1, 0, true, "0", true, TestName = "Валидное целое число")] | ||
| [TestCase(4, 2, true, "+1.23", true, TestName = "Валидное число где знак и цифры укладываются в precision")] | ||
| [TestCase(6, 2, true, "+1,23", true, TestName = "Валидное число через запятую")] | ||
| public void IsValidNumber_WhenValidInputProvided_ShouldReturnTrue(int precision, int scale, bool onlyPositive, string input, bool expectedResult) | ||
| { | ||
| var validator = new NumberValidator(precision, scale, onlyPositive); | ||
| var result = validator.IsValidNumber(input); | ||
|
|
||
| result | ||
| .Should() | ||
| .BeTrue( | ||
| $"Ожидалось, что '{input}' будет валидным при precision={precision}, scale={scale}, onlyPositive={onlyPositive}" | ||
| ); | ||
| } | ||
|
|
||
| [TestCase(3, 2, true, "00.00", false, TestName = "Ошибка: вышло за пределы precision")] | ||
| [TestCase(4, 2, true, "-0.00", false, TestName = "Ошибка: отрицательное число при onlyPositive=true")] | ||
| [TestCase(3, 2, true, "+0.00", false, TestName = "Ошибка: превышена точность из-за знака")] | ||
| [TestCase(6, 2, true, "0.000", false, TestName = "Ошибка: дробная часть превышает scale")] | ||
| [TestCase(3, 2, true, "a.sd", false, TestName = "Ошибка: нечисловая строка")] | ||
| public void IsValidNumber_WhenInvalidInputProvided_ShouldReturnFalse(int precision, int scale, bool onlyPositive, string input, bool expectedResult) | ||
| { | ||
| var validator = new NumberValidator(precision, scale, onlyPositive); | ||
| var result = validator.IsValidNumber(input); | ||
|
|
||
| ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0")); | ||
| ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0")); | ||
| ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("00.00")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-0.00")); | ||
| ClassicAssert.IsTrue(new NumberValidator(17, 2, true).IsValidNumber("0.0")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+0.00")); | ||
| ClassicAssert.IsTrue(new NumberValidator(4, 2, true).IsValidNumber("+1.23")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("+1.23")); | ||
| ClassicAssert.IsFalse(new NumberValidator(17, 2, true).IsValidNumber("0.000")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("-1.23")); | ||
| ClassicAssert.IsFalse(new NumberValidator(3, 2, true).IsValidNumber("a.sd")); | ||
| result | ||
| .Should() | ||
| .BeFalse( | ||
| $"Ожидалось, что '{input}' будет невалидным при precision={precision}, scale={scale}, onlyPositive={onlyPositive}" | ||
| ); | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
А можно ли как-то учитывать только поле Id?
И можно ли написать этот тест так, чтобы при переименовании Id на например Identificator тест все-равно работал правильно?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Через .Including можно выбрать поля которые мы хоти сравнивать и сравнивать только их
На второй вопрос не знаю как сделать, чтобы при переименовании тест все равно понимал, что исключать, но к id обращаться через аксессор get, и тогда сразу должна выпасть ошибка и мы поймем что он не нашел поле id, но вообще если именование правильное зачем его менять в будущем?