Ответы пользователя по тегу Spring
  • Как тестировать слой контроллера в Spring Boot с Mockito?

    @postya Автор вопроса
    Нашел такое решение:

    import ga.rusanov.backend.model.Video;
    import ga.rusanov.backend.service.VideoService;
    import org.junit.jupiter.api.BeforeEach;
    import org.junit.jupiter.api.Test;
    import org.mockito.Mockito;
    import org.mockito.MockitoAnnotations;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
    import org.springframework.boot.test.mock.mockito.MockBean;
    import org.springframework.test.web.servlet.MockMvc;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import static org.hamcrest.Matchers.hasSize;
    import static org.mockito.BDDMockito.given;
    import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
    import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
    
    @WebMvcTest(controllers = VideoController.class)
    class VideoControllerTest {
    
    
        @MockBean
        private VideoService videoService;
    
        @Autowired
        private MockMvc mockMvc;
    
        private List<Video> videoList;
    
        @BeforeEach()
         void setUp() throws Exception {
            MockitoAnnotations.initMocks(this);
    
            this.videoList = new ArrayList<>();
            this.videoList.add(new Video(1, "kultas", "https://webnsdf"));
            this.videoList.add(new Video(2, "joshua", "https://343heth"));
            this.videoList.add(new Video(3, "ambient mix", "https://ambientsome"));
        }
    
        @Test
        void shouldGetAllVideos() throws Exception{
    
            Mockito.when(videoService.findAll()).thenReturn(videoList);
    
            given(videoService.findAll()).willReturn(videoList);
            this.mockMvc.perform(get("/api/video/all"))
                    .andExpect(status().isOk())
                    .andExpect(jsonPath("$.*", hasSize(3)));
        }
    }
    Ответ написан
    Комментировать
  • Как показать уведомление с анимацией без перезагрузки встраницы после сохранения формы в Spring Boot?

    @postya Автор вопроса
    Нашёл библиотеку Toastr, всё работает так, как надо.
    Вот ,что имею на выходе:

    Метод,который сохраняет поля в БД:

    @PostMapping("/sketches/add")
        public String addSketch(
                                @Valid Sketch sketch,
                                BindingResult result,
                                RedirectAttributes redirectAttributes) {
    
            redirectAttributes.addFlashAttribute("action", "save");
            if (result.hasErrors()) {
                return "admin/add-sketch";
            }
           sketchRepository.save(sketch);
            return "redirect:/admin/sketches/add";
        }


    Подключение бибилотеки Toastr в html файле:

    <link rel="stylesheet" th:href="@{/libs/toastr/toastr.min.css}">
    
        <script th:src="@{/libs/jquery/jquery-3.4.1.min.js}"></script>
        <script defer th:src="@{/libs/toastr/toastr.min.js}"></script>
        <script defer th:src="@{/js/add-sketch.js}"></script>


    Настройки для библиотеки Toastr в отдельном файле add-sketch.js:

    /*TOASTR OPTIONS*/
    toastr.options = {
        "closeButton": false,
        "debug": false,
        "newestOnTop": false,
        "progressBar": false,
        "positionClass": "toast-bottom-right",
        "preventDuplicates": false,
        "onclick": null,
        "showDuration": "300",
        "hideDuration": "1000",
        "timeOut": "2000",
        "extendedTimeOut": "1000",
        "showEasing": "swing",
        "hideEasing": "linear",
        "showMethod": "fadeIn",
        "hideMethod": "fadeOut"
    };


    Вызов скрипта библиотеки в конце html файла:

    <script th:inline="javascript">
        $(document).ready(function () {
            var action = [[${action}]];
            if (action === 'save') {
                toastr["success"]("Success!")
            }
        });
    </script>
    Ответ написан
    Комментировать
  • Как подставить класс в Thymeleaf?

    @postya Автор вопроса
    Пока нашёл такое решение:

    Добавил ещё один url для редиректа в контроллере:

    @GetMapping("/home")
        public String home() {
            return "home";
        }
    
        @GetMapping("/")
        public String homePage() {
            return "forward:/home";
        }


    <ul class="header-links">
                <li th:class="${#httpServletRequest.requestURI.contains('/home')} ? 'link-active' : 'link-inactive'"><a th:href="@{/home}">Home</a></li>
                <li><a href="https://github.com/tttapa/Control-Surface" target="_blank">Get Library<i class="fab fa-github"></i></a></li>
                <li th:class="${#httpServletRequest.requestURI.contains('/examples')} ? 'link-active' : 'link-inactive'"><a th:href="@{/examples}">Sketch Examples</a></li>
                <li th:class="${#httpServletRequest.requestURI.contains('/tutorials')} ? 'link-active' : 'link-inactive'"><a th:href="@{/tutorials}">Video Tutorials</a></li>
            </ul>
    Ответ написан
    Комментировать
  • Как настроить в Spring Boot автоинкрементацию id в таблице PostgreSql с очисткой удаленных id?

    @postya Автор вопроса
    Благодарю всех ответивших на мой вопрос!
    Решение нашёл такое:

    Моя таблица в thymeleaf выглядит вот так:

    <table class="table table-bordered table-dark">
    
            </thead>
            <tbody>
                <tr>
                    <th scope="col" >ID</th>
                    <th scope="col">First Name</th>
                    <th scope="col">Last Name</th>
                    <th scope="col">Gender</th>
                    <th scope="col">Email</th>
                    <th scope="col">Section</th>
                    <th scope="col">Country</th>
                    <th scope="col">Edit</th>
                    <th scope="col">Delete</th>
                </tr>
    
                <tr th:each="student, iStat : ${list}">
                    <td th:text="${iStat.index + 1}"></td>
                    <td th:text="${student.firstName}"></td>
                    <td th:text="${student.lastName}"></td>
                    <td th:text="${student.gender}"></td>
                    <td th:text="${student.email}"></td>
                    <td th:text="${student.section}"></td>
                    <td th:text="${student.country}"></td>
    
                    <td><a th:href="@{'/editstudent/' + ${student.id}}">Edit</a></td>
                    <td><a th:href="@{'/deletestudent/' + ${student.id}}">Delete</a></td>
                </tr>
    
            </tbody>
        </table>


    Я всего лишь изменил в шаблонизаторе thymeleaf две строчки, было так:

    <tr th:each="student : ${list}">
                    <td th:text="${student.id}"></td>


    стало так:

    <tr th:each="student, iStat : ${list}">
                    <td th:text="${iStat.index + 1}"></td>
    Ответ написан
    Комментировать