Skip to content

Merge add-database#7

Merged
zephyr0021 merged 15 commits intomainfrom
add-database
May 5, 2025
Merged

Merge add-database#7
zephyr0021 merged 15 commits intomainfrom
add-database

Conversation

@zephyr0021
Copy link
Owner

Выполнил ТЗ 12 спринта


@Repository
@Primary
@Profile("!test")
Copy link

Choose a reason for hiding this comment

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

из тз

Вам предстоит реализовать интеграционное тестирование 
(англ. integration testing). С помощью него можно проверить 
работу приложения с зависимостями — например, с базой данных.

Предполагается, что UserDbStorage будет как раз работать с базой,
стоит его задействовать

Еще у нас две имплементации интерфейса и на обеих стоят аннотации Primary.
В классах, где делаем инджект зависимости через интерфейс UserStorage, можно использовать аннотацию Qualifier, например

@Service
@Slf4j
public class UserService {
    private final UserStorage userStorage;

    public UserService(@Qualifier("userDbStorage") UserStorage userStorage) {
        this.userStorage = userStorage;
    }
    // ...
}

тогда можно без Primary. Но Qualifier будет нужен везде, где инджектим в конструктор UserStorage

Copy link
Owner Author

Choose a reason for hiding this comment

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

Да тут я все понял, однако столкнулся с проблемой. У нас есть интеграционные тесты которые работают с БД - файл ru/yandex/practicum/filmorate/FilmoRateApplicationTests.java
И есть остальные тесты, которые тестируют отдельно контроллеры на inMemory базах, чтобы их разделить я использовал primary аннотации и профили, чтобы в ручную не переписывать в каждом сервисе конструктор

Copy link

Choose a reason for hiding this comment

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

Про FilmoRateApplicationTests понимаю,
но в целом реализация, когда на каждой имплементации стоит Primary, выглядит не очень хорошо

и что есть сервисы, которые запускаются только с тестовым профилем в интеграционных тестах. Зачем поддерживать сервисы, которые нужны только для тестов

стоит посоветоваться с наставником

Copy link
Owner Author

Choose a reason for hiding this comment

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

Поправил! Вы правы)

public Mpa(Long id, String name) {
this.id = id;
this.name = name;
}
Copy link

Choose a reason for hiding this comment

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

можно немного оптимизировать

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Mpa {

    private Long id;

    @NotBlank(message = "Название рейтинга не может быть пустым")
    private String name;

}

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

@NotBlank(message = "Название жанра не может быть пустым")
private String name;

public FilmGenre(Long id, String name) {
Copy link

Choose a reason for hiding this comment

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

тоже можно создать через AllArgsConstructor

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

Comment on lines +20 to +21
@Primary
@Profile("!test")
Copy link

Choose a reason for hiding this comment

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

в других классах тоже можно посмотреть

Copy link
Owner Author

Choose a reason for hiding this comment

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

Ответил выше

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

Comment on lines +18 to +19
1L, new Mpa(1L, "PG"),
2L, new Mpa(2L, "R-17")
Copy link

Choose a reason for hiding this comment

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

предварительно добавленные данные можно убрать
и InMemory классы не использовать в интеграционных тестах

Copy link
Owner Author

Choose a reason for hiding this comment

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

Добавленные данные необходимы для inMemory хранилищ чтобы смоделировать уже готовую БД с mpa. InMemory классы не используются в интеграционных тестах

Copy link
Owner Author

Choose a reason for hiding this comment

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

Исправил

Comment on lines +4 to +7
spring.datasource.url=
spring.datasource.driverClassName=
spring.datasource.username=
spring.datasource.password= No newline at end of file
Copy link

Choose a reason for hiding this comment

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

нужна h2

Copy link
Owner Author

Choose a reason for hiding this comment

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

Тут стоит профиль "test" он используются для обычных тестов контроллеров. Не для интеграционных тестов и не для прода, там БД нам не нужна, поэтому таким образом я убрал подключение к БД

Copy link
Owner Author

Choose a reason for hiding this comment

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

Убрал

@zephyr0021 zephyr0021 requested a review from z8q May 4, 2025 09:12
@Repository
@Primary
@Profile("!test")
@Repository("UserDbStorage")
Copy link

Choose a reason for hiding this comment

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

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

@zephyr0021 zephyr0021 merged commit cc031ba into main May 5, 2025
2 checks passed
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