Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @WebMvcTest(CategoryController.class)
- public class CategoryControllerTest {
- @MockBean
- CategoryService categoryService;
- ObjectMapper mapper = new ObjectMapper();
- @Autowired
- private MockMvc mockMvc;
- Category category;
- CategoryDto categoryDto;
- @BeforeEach
- public void init() {
- categoryDto = new CategoryDto();
- categoryDto.setId(15L);
- categoryDto.setName("name");
- categoryDto.setParentId(2L);
- category = new Category();
- category.setId(categoryDto.getId());
- category.setName(categoryDto.getName());
- category.setParentId(categoryDto.getParentId());
- }
- @Test
- public void is_should_return_created_category() throws Exception {
- when(categoryService.createCategory(any(CategoryDto.class))).thenReturn(categoryDto);
- mockMvc.perform(post("/api/categories/create")
- .content(mapper.writeValueAsString(categoryDto))
- .contentType(MediaType.APPLICATION_JSON))
- .andExpect(status().isOk())
- .andExpect(jsonPath("$.id").value(categoryDto.getId()))
- .andExpect(jsonPath("$.name").value(categoryDto.getName()))
- .andExpect(jsonPath("$.parentId").value(categoryDto.getParentId()));
- }
- }
- @Override
- @Transactional
- public CategoryDto createCategory(CategoryDto categoryDto) {
- Category category = categoryMapper.toEntity(categoryDto);
- categoryRepository.save(category);
- categoryDto.setId(category.getId());
- return categoryDto;
- }
- @Data
- @JsonInclude(JsonInclude.Include.NON_NULL)
- public class CategoryDto {
- private Long id;
- @NotEmpty
- private String name;
- private Long parentId;
- }
- @Entity
- @Table(name = "categories")
- @Getter
- @Setter
- public class Category extends BaseEntity {
- @Column(name = "name")
- private String name;
- @Column(name = "parent_id")
- private Long parentId;
- }
- @PostMapping("/create")
- public ResponseEntity<CategoryDto> createCategory(@RequestBody @Valid CategoryDto categoryDto) {
- return ResponseEntity.ok(categoryService.createCategory(categoryDto));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement