-
Notifications
You must be signed in to change notification settings - Fork 306
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
Вильданов Савелий #241
base: master
Are you sure you want to change the base?
Вильданов Савелий #241
Conversation
public Rectangle PutNextRectangle(Size rectangleSize) | ||
{ | ||
Rectangle rectangle; | ||
if (rectangleSize.Width < 0 || rectangleSize.Height < 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.
А есть ли смысл работать с нулевой шириной или высотой?
cs/TagsCloudVisualization/Spiral.cs
Outdated
angle = 0; | ||
} | ||
|
||
public Point getNextPointOnSpiral() |
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.
Публичный метод с маленькой буквы
private List<Rectangle> rectangles; | ||
private Spiral spiral; |
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.
Эти поля тоже можно readonly сделать
[Test] | ||
public void PutNextRectangle_ShouldAddNewRectangle() | ||
{ | ||
CircularCloudLayouter circularCloudLayouter = new CircularCloudLayouter(new Point()); |
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.
Создание этого класса происходит во всех тестах этого класса - можно вынести в SetUp
, как обязательное действие перед прогоном теста. Плюсом будет то, что код самих тестов станет читать попроще
CircularCloudLayouter circularCloudLayouter = new CircularCloudLayouter(new Point()); | ||
circularCloudLayouter.PutNextRectangle(new Size(2, 2)); | ||
circularCloudLayouter.GetRectangles().Should().Contain(new Rectangle(-1, -1, 2, 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.
По выполняемым в тесте действиям этот тест идентичен предыдущему, а значит и проверку из этого теста можно включить в предыдущий
} | ||
|
||
[Test] | ||
public void PutNextRectangle_ShouldHaveCorrectSize() |
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.
Из названия теста не совсем понятно, Size
чего будет проверяться в тесте - размещенного прямоугольника или коллекции с размещенными прямоугольниками
public class CircularCloudLayotherTest | ||
{ | ||
[TestCase(-2, 3, TestName = "Negative width")] | ||
[TestCase(-2, 3, TestName = "Negative height")] |
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.
В Negative height
тесте высота положительная)
[Test] | ||
public void getNextPointOnSpiral_ShouldReturnNextPointOnSpiral() |
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.
Давай тест на несколько размещаемых точек ещё напишем
|
||
namespace TagsCloudVisualization.TagsCloudVisualizationTests; | ||
|
||
public class CircularCloudLayotherTest |
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.
Было бы круто ещё написать тест на вставку ооооочень большого количества прямоугольников, проверим, что он отработает за некоторое вменяемое время
Проверок внутри не нужно будет, у Nunit есть атрибут, который завершит тест, если тот не уложится в заданное время
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.
Хорошей практикой считается разделять тесты и основной код на отдельные проекты, так ты не нагружаешь процесс сборки основного кода лишними зависимостями. На больших проектах с тысячами тестов это может значительно сказаться на производительности.
Давай и тут выделим под тесты отдельный проект
Bitmap bmp = new Bitmap(1000, 1000); | ||
Graphics newGraphics = Graphics.FromImage(bmp); | ||
var backgroundBrush = new SolidBrush(Color.White); | ||
var rectanglePen = new Pen(Color.Black); |
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.
Все ли ресурсы тут освобождены после того, как они стали не нужными?
|
||
namespace TagsCloudVisualization; | ||
|
||
public static class CloudGenerator |
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.
Этот класс взвалил на себя две ответственности - он и прямоугольники генерирует, и в файл сохраняет, а это все же разные ответственности. Давай сохранение в файл вынесем в отдельный модуль. А метод GenerateRectangles
просто запишем в Program.cs
как обычный вызывающий код
|
||
namespace TagsCloudVisualization.TagsCloudVisualizationTests; | ||
|
||
public class CloudGeneratorTest |
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.
Этот класс тестировать не обязательно (именно ту часть, которая просто вызывает лейаутер и его построение), так как это не основной код твоей программы. Он просто вызывает основные модули и методы в определенном порядке. А после вынесения в Program.cs
и тестировать будет нечего))
А вот тест на сохранение в файл тест можно будет оставить
CircularCloudLayouter circularCloudLayouter = | ||
new CircularCloudLayouter(new Point(CloudLayouterConst.CloudCentreX, CloudLayouterConst.CloudCentreY)); | ||
circularCloudLayouter.PutNextRectangle(new Size(2, 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.
Это лишняя работа в тесте. Когда тестируем сохраняльщик в файл, то нам не важно, откуда взялись прямоугольники, нам важно просто их нарисовать. Поэтому можешь тут просто руками создать список, лейаутер вызывать не нужно
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="FluentAssertions" Version="7.0.0-alpha.5" /> |
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.
альфа пакеты на свой страх и риск))
Bitmap bmp = new Bitmap(1000, 1000); | ||
Graphics newGraphics = Graphics.FromImage(bmp); | ||
var backgroundBrush = new SolidBrush(Color.White); | ||
var rectanglePen = new Pen(Color.Black); |
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.
Все ещё не освободил ресурсы тут
using var bmp = new Bitmap(1000, 1000);
using var newGraphics = Graphics.FromImage(bmp);
using var backgroundBrush = new SolidBrush(Color.White);
using var rectanglePen = new Pen(Color.Black);
Классы, которые реализуют IDisposable
можно с помощью синтакисческого сахара диспоузить через using
, когда они завершат выполнение в своем скоупе
{ | ||
public static Bitmap DrawRectangles(List<Rectangle> rectangles) | ||
{ | ||
Bitmap bmp = new Bitmap(1000, 1000); |
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.
Если прямоугольников будет много, они могут просто не влезть в этот размер, почему именно 1000 на 1000?
newGraphics.DrawRectangle(rectanglePen, rectangle); | ||
} | ||
|
||
newGraphics.Dispose(); |
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.
Это можно убрать, юзинга будет достаточно
@@ -9,6 +9,7 @@ | |||
</PropertyGroup> | |||
|
|||
<ItemGroup> | |||
<PackageReference Include="FluentAssertions" Version="6.12.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.
А зачем пакет для ассертов в проекте, где он не будет использоваться?
@@ -5,10 +5,11 @@ | |||
<TargetFramework>net8.0</TargetFramework> | |||
<ImplicitUsings>enable</ImplicitUsings> | |||
<Nullable>enable</Nullable> | |||
<RootNamespace>TagsCloudVisualisationTests</RootNamespace> |
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.
Можно не добавлять, по умолчанию RootNamespace
равен названию проекта
|
||
namespace TagsCloudVisualization.TagsCloudVisualizationTests; | ||
|
||
public class CloudDrawerTest |
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.
Это название уже не актуально, по факту внутри тестируется не CloudDrawer
|
||
namespace TagsCloudVisualization; | ||
|
||
public class SaveImages |
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.
Классы называем существительными, сейчас у тебя получился глагол "Сохрани изображения", а надо "Сохранятель изображений"))
@desolver