Friday, August 1, 2025

Testing controller

------Controller-------------

@RestController
@RequestMapping("/items")
public class ItemController {
    private final ItemService itemService;    

@Autowired
    public ItemController(ItemService itemService) {
        this.itemService = itemService;
    }
    @GetMapping
    public ResponseEntity<List<Item>> getAllItems() {
        List<Item> allItems = itemService.findAllItems();
        return ResponseEntity.ok(allItems);
    }
}

----------Service---------

@Slf4j
@Service
public class ItemServiceImpl implements ItemService {
    @Override
    public List<Item> findAllItems() {
        return Arrays.asList(new Item(BigInteger.valueOf(1), "pen", 10), new Item(BigInteger.valueOf(2), "pencil", 5));
    }
}
 

Now we want to test ItemController. we can do this by the below way ----

-------Test code---------------------

@WebMvcTest(ItemController.class) // load only mvc part not full app.
public class ItemControllerTest {
    @Autowired
    private MockMvc mockMvc; // can simulate http request without start server
    @MockBean
    private ItemService itemService;
    @Test
    void testFindAllItems() {
        // arrange
        List<Item> items = Arrays.asList(new Item(BigInteger.valueOf(1), "pen", 10),
                new Item(BigInteger.valueOf(2), "pencil", 5));
        when(itemService.findAllItems()).thenReturn(items);//stub so no actual method .
        try {
            // act
            ResultActions resultActions = mockMvc.perform(get("/items").contentType(MediaType.APPLICATION_JSON));
            // assert
            resultActions.andExpect(status().isOk())
            .andExpect(jsonPath("$.size()").value(2))
                    .andExpect(jsonPath("$[0].title").value("pen"))
                    .andExpect(jsonPath("$[1].price").value(5));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Notes:
--------

 1.@WebMvcTest(ItemController.class) : Load only MVC part not full app.

2. MockMvc :  Can simulate HTTP request without start server.

3. . $ : Root of the response json.

 

No comments:

Post a Comment

Testing controller

------Controller------------- @RestController @RequestMapping("/items") public class ItemController {     private final ItemServic...