-
Notifications
You must be signed in to change notification settings - Fork 282
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
Яценко Ирина #235
base: master
Are you sure you want to change the base?
Яценко Ирина #235
Changes from 5 commits
2c1d986
3938cbe
d229179
09348a8
5f3e0e4
6eb6ff0
2146ede
8832ca8
def3bbb
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,34 +1,80 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Runtime.CompilerServices; | ||
using System.Text.RegularExpressions; | ||
using FluentAssertions; | ||
using NUnit.Framework; | ||
|
||
namespace HomeExercises | ||
{ | ||
public class NumberValidatorTests | ||
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.
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. Ранее об этом не говорил, но класс тоже можно пометить атрибутом |
||
{ | ||
private static IEnumerable<TestCaseData> ArgumentExceptionTestCases | ||
{ | ||
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. Очевидно, что слетело форматирование. Если пользуешься |
||
get | ||
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. Зачем тут геттер?) |
||
{ | ||
yield return new TestCaseData(-1, 2, true).SetName("WhenPassNegativePrecision"); | ||
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. Зачем тут |
||
yield return new TestCaseData(1, -2, true).SetName("WhenPassNegativeScale"); | ||
yield return new TestCaseData(2, 2, true).SetName("WhenPrecisionIsEqualToTheScale"); | ||
} | ||
} | ||
|
||
[TestCaseSource(nameof(ArgumentExceptionTestCases))] | ||
public void NumberValidatorCtor_WhenPassInvalidArguments_ShouldThrowArgumentException(int precision, | ||
int scale, bool onlyPositive) | ||
{ | ||
TestDelegate testDelegate = () => new NumberValidator(precision, scale, onlyPositive); | ||
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. Всё тело метода можно упростить до одной строчки, не забудь про |
||
|
||
Assert.Throws<ArgumentException>(testDelegate); | ||
} | ||
|
||
[Test] | ||
public void Test() | ||
public void NumberValidatorCtor_WhenPassValidArguments_ShouldNotThrows() | ||
{ | ||
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")); | ||
TestDelegate testDelegate = () => new NumberValidator(1, 0, true); | ||
|
||
Assert.DoesNotThrow(testDelegate); | ||
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. Тут тоже можно до одной строки упростить. |
||
} | ||
} | ||
|
||
private static IEnumerable<TestCaseData> InvalidArgumentTestCases | ||
{ | ||
get | ||
{ | ||
yield return new TestCaseData("a.sd", false).SetName("WhenLettersInsteadOfNumber"); | ||
yield return new TestCaseData("2.!", false).SetName("WhenSymbolsInsteadOfNumber"); | ||
yield return new TestCaseData(null!, false).SetName("WhenPassNumberIsNull"); | ||
yield return new TestCaseData("", false).SetName("WhenPassNumberIsEmpty"); | ||
yield return new TestCaseData("-0.00", false).SetName("WhenIntPartWithNegativeSignMoreThanPrecision"); | ||
yield return new TestCaseData("+1.23", false).SetName("WhenIntPartWithPositiveSignMoreThanPrecision"); | ||
yield return new TestCaseData("0.000", false).SetName("WhenFractionalPartMoreThanScale"); | ||
} | ||
} | ||
private static IEnumerable<TestCaseData> ValidArgumentTestCases | ||
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. Помимо уже озвученных замечаний |
||
{ | ||
get | ||
{ | ||
yield return new TestCaseData("0", true).SetName("WhenFractionalPartIsMissing"); | ||
yield return new TestCaseData("0.0", true).SetName("WhenNumberIsValid"); | ||
} | ||
} | ||
|
||
private NumberValidator numberValidator; | ||
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. Тоже как вариант обобщения. Иногда Помимо прочего, не беря во внимание По тому, как я бы хотел видеть создание К слову, поля обычно начинается с нижнего подчеркивания: |
||
|
||
[SetUp] | ||
public void SetUp() | ||
{ | ||
numberValidator = new NumberValidator(3, 2, true); | ||
} | ||
|
||
[TestOf(nameof(NumberValidator.IsValidNumber))] | ||
[TestCaseSource(nameof(ValidArgumentTestCases))] | ||
[TestCaseSource(nameof(InvalidArgumentTestCases))] | ||
public void WhenPassInvalidArguments_ShouldReturnFalse(string number, bool expectedResult) | ||
{ | ||
var actualResult = numberValidator.IsValidNumber(number); | ||
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. Ещё один минус |
||
|
||
Assert.AreEqual(expectedResult, actualResult); | ||
} | ||
} | ||
|
||
public class NumberValidator | ||
{ | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,81 +3,82 @@ | |
|
||
namespace HomeExercises | ||
{ | ||
public class ObjectComparison | ||
{ | ||
[Test] | ||
[Description("Проверка текущего царя")] | ||
[Category("ToRefactor")] | ||
public void CheckCurrentTsar() | ||
{ | ||
var actualTsar = TsarRegistry.GetCurrentTsar(); | ||
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)); | ||
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); | ||
actualTsar.Should() | ||
.BeEquivalentTo(expectedTsar, x => x | ||
.Excluding(x => x.Id) | ||
.Excluding(x => x.Parent!.Id)); | ||
} | ||
|
||
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)); | ||
|
||
[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)); | ||
// Какие недостатки у такого подхода? | ||
// Данный подход делает класс труднорасширяемым, ведь при добавлении новых полей в класс Person | ||
// нужно переписывать и метод сравнения для всех этих полей, так же новые поля cможет добавить | ||
// другой разработчик, который не знает о таком методе сравнения, что приведет к новым, неотловоенным ошибкам - | ||
// новые поля не будут сравниваться. | ||
// В моем решении (CheckCurrentTsar), такой ошибки не возникнет и класс Person сможет без ошибок расширяться | ||
// при условии, что сравниваться будут все поля, кроме Id (так же и их Parent), так как код написан не перебиранием | ||
// всех полей для сравнения, а сравнением объекта в целом с исключением его Id. | ||
Assert.True(AreEqual(actualTsar, expectedTsar)); | ||
} | ||
|
||
// Какие недостатки у такого подхода? | ||
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); | ||
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. Ранее не обратил внимание, но объясни ещё, пж, про 52 строку - в чем тут потенциальная опасность? |
||
} | ||
} | ||
|
||
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); | ||
} | ||
} | ||
public class TsarRegistry | ||
{ | ||
public static Person GetCurrentTsar() | ||
{ | ||
return new Person( | ||
"Ivan IV The Terrible", 54, 170, 70, | ||
new Person("Vasili III of Russia", 28, 170, 60, null)); | ||
} | ||
} | ||
|
||
public class TsarRegistry | ||
{ | ||
public static Person GetCurrentTsar() | ||
{ | ||
return new Person( | ||
"Ivan IV The Terrible", 54, 170, 70, | ||
new Person("Vasili III of Russia", 28, 170, 60, null)); | ||
} | ||
} | ||
public class Person | ||
{ | ||
public static int IdCounter = 0; | ||
public int Age, Height, Weight; | ||
public string Name; | ||
public Person? Parent; | ||
public int Id; | ||
|
||
public class Person | ||
{ | ||
public static int IdCounter = 0; | ||
public int Age, Height, Weight; | ||
public string Name; | ||
public Person? Parent; | ||
public int Id; | ||
|
||
public Person(string name, int age, int height, int weight, Person? parent) | ||
{ | ||
Id = IdCounter++; | ||
Name = name; | ||
Age = age; | ||
Height = height; | ||
Weight = weight; | ||
Parent = parent; | ||
} | ||
} | ||
public Person(string name, int age, int height, int weight, Person? parent) | ||
{ | ||
Id = IdCounter++; | ||
Name = name; | ||
Age = age; | ||
Height = height; | ||
Weight = weight; | ||
Parent = parent; | ||
} | ||
} | ||
} |
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.
Круто, что коммиты логически разбиты