Тесты - oyboy/Jora GitHub Wiki

Тест home-страницы

Предполагает только возможность на неё попасть:

@Test
    public void testStartPage() throws Exception{
        this.mockMvc.perform(get("/home"))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("My Projects")));
    }

Создание проекта

Тестируется валидация полей и сохранение в базу новой сущности

@SpringBootTest
@AutoConfigureMockMvc
@TestPropertySource("/application-test.properties")
public class CreateProjectTest {
    @Autowired
    MockMvc mockMvc;
    @Autowired
    ProjectRepository projectRepository;
    @BeforeEach
    public void setup() {
        projectRepository.deleteAll();
    }
    private String generateText(int n){
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < n; i++) builder.append(i);
        return builder.toString();
    }
    @Test
    public void testTitleCannotBeEmpty() throws Exception{
        this.mockMvc.perform(post("/home/create")
                .param("title", "")
                .param("description", "Some description"))
                .andExpect(model().attributeHasFieldErrors("project", "title"))
                .andExpect(model().attributeExists("errors"))
                .andExpect(view().name("create-project"));
    }
    @Test
    public void testBothFieldsCannotBeTooLong() throws Exception{
        this.mockMvc.perform(post("/home/create")
                        .param("title", generateText(51))
                        .param("description", generateText(260)))
                .andExpect(model().attributeHasFieldErrors("project", "title"))
                .andExpect(model().attributeHasFieldErrors("project", "description"))
                .andExpect(model().attributeExists("errors"))
                .andExpect(view().name("create-project"));
    }
    @Test
    public void testSuccessfulCreation() throws Exception {
        mockMvc.perform(post("/home/create")
                        .param("title", "Usual title")
                        .param("description", "Some description"))
                .andExpect(redirectedUrl("/home"));

        assertEquals(1, projectRepository.count());
    }
}