-
Notifications
You must be signed in to change notification settings - Fork 32
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
Шестопалов Андрей #18
base: master
Are you sure you want to change the base?
Conversation
var ex = Assert.Throws<ArgumentException>(action, | ||
$"Failed: Expected ArgumentException for precision = {precision}"); | ||
|
||
Assert.That(ex.Message, Is.EqualTo("precision must be a positive number"), |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
{ | ||
TestDelegate action = () => new NumberValidator(precision); | ||
|
||
var ex = Assert.Throws<ArgumentException>(action, |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
[TestCase(-100)] | ||
[TestCase(-9999)] | ||
[Category("InitializationTests")] | ||
public void Constructor_ScaleIsNegative_ThrowArgumentException(int scale) |
This comment was marked as resolved.
This comment was marked as resolved.
Sorry, something went wrong.
[Category("InitializationTests")] | ||
public void Constructor_InvalidArguments_ThrowArgumentException(int precision, int scale, string expectedMessage) | ||
{ | ||
Action action = () => new NumberValidator(precision, scale); |
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.
Action -> var. И по смыслу это Func так как возвращает результат.
Предпочтительно использовать ключевое слово var. Явно указывать тип излишне, компилятор умеет определять тип динамически. Так же это позволит сократить код и сделать его более читаемым
[TestCase(1, 2, "scale must be a non-negative number less or equal than precision", | ||
TestName = "Constructor_PrecisionIsGreaterThanPrecision_ThrowArgumentException (precision = 1, scale = 2)")] | ||
[Category("InitializationTests")] | ||
public void Constructor_InvalidArguments_ThrowArgumentException(int precision, int scale, string expectedMessage) |
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.
Проверять сообщение ошибки в тесте не самая лучшая практика. Тест становиться не устойчивым к законным изменениям в NumberValidator. При каждом изменении сообщения придется править тест
|
||
namespace HomeExercise.Tasks.NumberValidator; | ||
|
||
[TestFixture] | ||
public class NumberValidatorTests | ||
{ | ||
[Test] | ||
public void Test() | ||
#region ConstructorTests |
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.
Предлагаю убрать использование #region.
Это вызывает затруднение при навигации, лишние клики
Большинство Ide поддерживают скрытие блоков кода, если в этом есть необходимость.
И на практике использование region указывает на плохо декомпозированный код.
Альтернативой может послужить рефакторинг кода, переиспользуемые методы, вынесение в отдельный или partial класс
[TestCase(5, 2, "+21", | ||
TestName = "IsValidNumber_IntegerWithSign_ScaleIsGreaterThanZero_ReturnsTrue (precision = 5, scale = 2, onlyPositive = false, valueForValidation = \"+37\")")] | ||
[Category("IntegersTests")] | ||
public void IsValidNumber_IntegerWithinPrecisionAndScale_ReturnTrue(int precision, int scale, string valueForValidation) |
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.
Тест дублирует логику теста ниже. За исключением onlyPositive в конструкторе NumberValidator.
Предлагаю передавать значение onlyPositive в TestCase
[Category("IntegersTests")] | ||
public void IsValidNumber_IntegerWithinPrecisionAndScale_ReturnTrue(int precision, int scale, string valueForValidation) | ||
{ | ||
var validator = new NumberValidator(precision, scale, false); |
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.
В текущей реализации излишне явно проставлять onlyPositive false. Оно и так определено как false по умолчанию в конструкторе
|
||
#region IntegersTests | ||
[TestCase(1, 0, "0", | ||
TestName = "IsValidNumber_IntegerWithoutSign_LengthEqualsPrecision_ReturnsTrue (precision = 1, scale = 0, onlyPositive = false, valueForValidation = \"0\")")] |
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.
Указывать параметры тест-кейса еще и в нейминге - излишнее дублирование. Это затрудняет читаемость теста и смещает фокус с самого главного - что проверяет тест. Если тест падает, то разработчик пойдет чинить и увидит сигнатуру теста
var validator = new NumberValidator(precision, scale, false); | ||
var isValid = validator.IsValidNumber(valueForValidation); | ||
|
||
isValid.Should().BeTrue(); |
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.
Дублирование кода метода ниже за исключением ожидаемого результата. Предлагаю передавать ожидаемый результат в параметрах теста
TestName = "IsValidNumber_InputIsWhitespace_ReturnFalse (precision = 5, scale = 2, onlyPositive = false, valueForValidation = \" \")")] | ||
[TestCase(5, 2, "\t", | ||
TestName = "IsValidNumber_InputIsEscapeSequences_ReturnFalse (precision = 5, scale = 2, onlyPositive = false, valueForValidation = \"\\t\")")] | ||
|
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.
Лишние пробелы между атрибутами
[TestCase(5, 2, "636.", | ||
TestName = "IsValidNumber_DecimalWithoutFraction_ScaleIsPositive_ReturnsFalse (precision = 5, scale = 2, onlyPositive = false, valueForValidation = \"636.\")")] | ||
|
||
[Category("InvalidInputsTests")] |
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.
Расскажешь для чего используется атрибут Category?
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.
Как написано в интернете, через него можно запускать отдельные группы тестов
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.
Все верно, можно запускать прогон тестов по отдельным категориям. Не нашел кода который бы это как-то использовал и для чего тебе это тут понадобилось, если, скорее всего, нужно прогнать все тесты разом?
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.
Согласен, в данном случае это не использую.
В первой задаче (ObjectComparison) на тестовом методе был атрибут [Category("ToRefactor")]. Я тоже не нашёл где бы он использовался, но посчитал, что раз он использован в показательном примере первой задачи, то можно добавить этот атрибут и в моих методах.
[TestCase(1, 2, "scale must be a non-negative number less or equal than precision", | ||
TestName = "Constructor_PrecisionIsGreaterThanPrecision_ThrowArgumentException (precision = 1, scale = 2)")] | ||
[Category("InitializationTests")] | ||
public void Constructor_InvalidArguments_ThrowArgumentException(int precision, int scale, string expectedMessage) |
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.
Предлагаю отрефакторить имена тестов
Метод назвать ThrowException_When, а тесты PrecisionEqualsScale и т.д
Повысим читаемость, уберём дублирование
[TestCase(5, 5, "scale must be a non-negative number less or equal than precision", | ||
TestName = "Constructor_PrecisionEqualsScale_ThrowArgumentException (precision = 5, scale = 5)")] | ||
[TestCase(1, 2, "scale must be a non-negative number less or equal than precision", | ||
TestName = "Constructor_PrecisionIsGreaterThanPrecision_ThrowArgumentException (precision = 1, scale = 2)")] |
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.
PrecisionIsGreaterThanPrecision - опечатка?
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.
Да.
No description provided.