Skip to content

Шагов Владислав#53

Open
ShagovVladislav wants to merge 5 commits intokontur-courses:masterfrom
ShagovVladislav:master
Open

Шагов Владислав#53
ShagovVladislav wants to merge 5 commits intokontur-courses:masterfrom
ShagovVladislav:master

Conversation

@ShagovVladislav
Copy link

using NUnit.Framework;
using FluentAssertions;
using NUnit.Framework;
using NUnit.Framework.Legacy;
Copy link

Choose a reason for hiding this comment

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

using NUnit.Framework.Legacy; не используется

Copy link
Author

Choose a reason for hiding this comment

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

если убрать - альтернативное решение не сможет использовать ClassicAssert

Copy link

Choose a reason for hiding this comment

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

Не в том классе пометил - это к NumberValidatorTests.cs относилось, сорри.

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"));

Copy link

Choose a reason for hiding this comment

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

Пустая строка после каждого [Test], давай уберём, а перед атрибутом, наоборот, добавим.


public void NumberValidator_ThrowExc_AfterAdditionNotPositivePrecision()
{
var action1 = () => new NumberValidator(-1, 2, true);
Copy link

Choose a reason for hiding this comment

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

Давай вынесем action1 и action2 в атрибуты TestCase

var action2 = () => new NumberValidator(0, 2, true);

action1.Should().Throw<ArgumentException>()
.WithMessage("precision must be a positive number");
Copy link

Choose a reason for hiding this comment

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

Давай вынесем "precision must be a positive number" в константу. Иначе, если захотим исправить сообщение, придётся не забыть исправить в двух местах.

var action = () => new NumberValidator(1, 2, true);

action.Should().Throw<ArgumentException>()
.WithMessage("precision must be a non-negative number less or equal than precision");
Copy link

Choose a reason for hiding this comment

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

То же самое - "precision must be a non-negative number less or equal than precision" в константу.

Вопрос на засыпку: тебя в смысле этого сообщения ничего не смущает? :)

Copy link
Author

Choose a reason for hiding this comment

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

scale вместо первого precision. Я думал может поменять, но не стал, ибо по заданию тот файл не трогаем

Copy link

Choose a reason for hiding this comment

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

Ага. Здесь мораль в том, что если есть что-то за пределами твоей задачи, что недорого поправить (а в этом случае недорого), то лучше поправить сразу. В противном случае получается, что мы добавили проверку конкретно этой строки в тесты и если её потом исправят в исходном классе, то неизвестно, сколько еще дополнительных правок придётся делать в тестах.

}
[Test]

public void NumberValidator_ThrowExc_AfterAdditionPositivePrecisionEqualScale()
Copy link

Choose a reason for hiding this comment

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

Тест полностью дублирует предыдущий. Если бы у тебя был один тест с разными тест-кейсами, то ты бы сразу увидел, что продублировал тест-кейс, давай объединим в один.

Кроме того, я вот читаю часть названия "...AfterAddition..." и чет не совсем понимаю, про что это?

А еще у тебя класс с тестами и так называется NumberValidatorTests и в целом встречается, когда в именовании теста пишут название тестируемого класса\модуля, но, кмк, будет лаконичнее написать просто Should_ThrowException_.... Да, слово exception я бы полностью написал.

public void NumberValidator_NotThrow_WhenValidParameters()
{

var action1 = () => new NumberValidator(1, 0, true);
Copy link

Choose a reason for hiding this comment

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

Выноси разные параметры для action в тест-кейсы


public void IsValidNumber_IsValid_AfterAdditionValidNumber()
{
var testNum1 = new NumberValidator(4, 2, true).IsValidNumber("12.34");
Copy link

Choose a reason for hiding this comment

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

Ты в тестах несколько нарушаешь структуру AAA - по-дефолту обычно Arrange отделяют пустой строкой от Act, а Act - пустой строкой от Assert. В целом это не критично и можно писать и так (и люди пишут), НО! Когда тесты становятся посложнее проще их читать, когда у них эта структура соблюдена.


public void IsValidNumber_IsNotValid_AfterAdditionNegativeNumberWhenOnlyPositiveTrue()
{
var testNum1 = new NumberValidator(4, 2, true).IsValidNumber("-2.34");
Copy link

Choose a reason for hiding this comment

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

Пиши тесты единообразно - если ты в предыдущих тестах отделял Assert пустой строкой, то и здесь делай так же.


[Test]

public void IsValidNumber_IsValid_AfterAdditionNegativeNumberWhenOnlyPositiveFalse()
Copy link

Choose a reason for hiding this comment

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

IsValidNumber_IsValid... - кмк, понятнее будет IsValidNumber_ReturnFalse....


actualTsar.Should().BeEquivalentTo(expectedTsar, options => options
.Excluding(t => t.Id)
.Excluding(t => t.Parent.Id));
Copy link

Choose a reason for hiding this comment

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

Дополнительный вопрос: а что будет, если начнут добавлять деда, прадеда и т.п?

Copy link
Author

Choose a reason for hiding this comment

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

Тест упадёт, так как у деда начнёт сравниваться Id. Вместо этого отключу сравнение id у всех объектов класса Person

Copy link

Choose a reason for hiding this comment

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

Вместо этого отключу сравнение id у всех объектов класса Person

А покажи, как?

Copy link
Author

Choose a reason for hiding this comment

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

actualTsar.Should().BeEquivalentTo(expectedTsar, options => options
.Excluding(t => t.Id)
.Excluding(t => t.Name == "Id" && t.DeclaringType == typeof(Person)));

Copy link

Choose a reason for hiding this comment

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

В принципе уже норм. Но можно докрутить решение, чтобы было достаточно только второго Excluding.

Copy link
Author

Choose a reason for hiding this comment

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

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

Copy link

Choose a reason for hiding this comment

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

Нельзя, т.к. если поле "Id" переименуют, то оно снова начнёт сравниваться. Пока у тебя есть первая строчка, ты сразу глядя на код поймёшь, в чём проблема (т.к. он тупо не скомпилируется, если в тесте не поменять название поля вместе с объявлением внутри класса, ну IDE обычно сейчас сразу во всех местах меняют).


using FluentAssertions;
using NUnit.Framework;
using NUnit.Framework.Legacy;
Copy link

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