Skip to content

Глейзер Роман - #39

Open
RomanGleyzer wants to merge 4 commits into
kontur-courses:masterfrom
RomanGleyzer:master
Open

Глейзер Роман#39
RomanGleyzer wants to merge 4 commits into
kontur-courses:masterfrom
RomanGleyzer:master

Conversation

@RomanGleyzer

Copy link
Copy Markdown


public class ObjectComparison
{
[Test]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Неинформативное название и описание. Не ясно что проверяется. Давай поправим

@@ -14,16 +16,14 @@ public void CheckCurrentTsar()
var expectedTsar = new Person("Ivan IV The Terrible", 54, 170, 70,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Давай явно укажем что значат эти параметры через named arguments, чтобы не приходилось проваливаться в конструктор Person чтобы разобраться что есть что

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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Давай поправим форматирование Fluent Assertions. Либо в одну строку, либо с правильными переносами для цепочки вызовов

// Какие недостатки у такого подхода?
// Недостатки подхода:
// 1) Требуется ручное обновление метода сравнения при добавлении новых свойств в класс Person,
// 2) Тест менее информативен при падении. Он просто укажет, что объекты не равны, не показывая какие именно свойства не совпали.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Могут ли быть проблемы с рекурсией?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Могут ли быть проблемы с рекурсией?

Да, попробовал сделать так, чтобы у обоих сравниваемых объектов родитель указывал на самого себя. В итоге метод сравнения убежал в бесконечную рекурсию:

image image

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"));
[TestCase(-1, 2, true, TestName = "Исключение, когда precision отрицательный")]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Много где testName избыточен, т.к. очевиден из переданных аргументов

[TestCase(5, -1, true, TestName = "Исключение, когда scale отрицательный")]
[TestCase(1, 2, true, TestName = "Исключение, когда scale больше precision")]
[TestCase(1, 1, true, TestName = "Исключение исключение, когда scale равен precision")]
public void Ctor_Should_Throw_On_Invalid_Arguments(int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше разбить на отдельные тесты по категориям (InvalidPrecision, InvalidScale и т.д.) для улучшения читабельности

[TestCase(5, -1, true, TestName = "Исключение, когда scale отрицательный")]
[TestCase(1, 2, true, TestName = "Исключение, когда scale больше precision")]
[TestCase(1, 1, true, TestName = "Исключение исключение, когда scale равен precision")]
public void Ctor_Should_Throw_On_Invalid_Arguments(int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

В нейминге лучше придерживаться шаблона Method_Scenario_ExpectedResult

public void Ctor_Should_Throw_On_Invalid_Arguments(int precision, int scale, bool onlyPositive)
{
var act = () => new NumberValidator(precision, scale, onlyPositive);
act.Should().Throw<ArgumentException>();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Можно еще текст ошибки уточнить

}

[TestCase(1, 0, true, TestName = "Не выбрасывает исключение на корректных элемент")]
public void Ctor_Should_Not_Throw_On_Valid_Arguments(int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

можно переписать без testCase, т.к. он один


[TestCase("", 17, 2, true, TestName = "Возвращает false, когда значение пустое")]
[TestCase(null, 17, 2, true, TestName = "Возвращает false, когда значение null")]
public void Should_Return_False_On_NullOrEmpty(string value, int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Лучше указывать имя метода в нейминге теста, т.к. в классе может быть несколько методов

[TestCase("4_4", 11, 3, true, TestName = "Возвращает false, когда число содержит символ подчёркивания")]
[TestCase("abcd_4", 10, 5, true, TestName = "Возвращает false, когда строка содержит буквы и подчёркивание")]
[TestCase("--1", 12, 2, true, TestName = "Возвращает false, когда число содержит двойной минус")]
public void Should_Return_False_On_InvalidFormat(string value, int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Тоже лучше разбить по категориям

public void IsValid_Respects_Scale(string input, int precision, int scale,
bool onlyPositive, bool expected)
{
var validator = new NumberValidator(10, scale, onlyPositive);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

магическое число

[TestCase(0, 2, true, TestName = "Исключение, когда precision равен нулю")]
[TestCase(5, -1, true, TestName = "Исключение, когда scale отрицательный")]
[TestCase(1, 2, true, TestName = "Исключение, когда scale больше precision")]
[TestCase(1, 1, true, TestName = "Исключение исключение, когда scale равен precision")]

@masssha1308 masssha1308 Oct 27, 2025

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Кое-где в TestName's есть очепятки, проверь, пожалуйста

ObjectComparison стал TsarComparison, добавил named arguments, поправил форматирование Fluent Assertions, выяснил, что могу быть проблемы с рекурсией
Убрал избыточный TestName, поправил опечатки, стал придерживаться нейминга Method_Scenario_ExpectedResult, добавил уточнения текстов ошибок, разбил тесты по категориям и избавился от магического числа
#region Некорректная дробность

[TestCase(5, -1, true)]
public void Ctor_InvalidScale_Negative_ThrowsArgumentException(int precision, int scale, bool onlyPositive)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Если TestCase один, то лучше не писать через TestCase, а написать просто тест

public class TsarComparison
{
[Test]
[Description("Проверка текущего царя")]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

категорию теста после рефакторинга можно убрать

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants