2

I want to test Rest Controller but not sure how to do it. Right now, I have a setup method, in which I delete all records from table ITEMS and input some records on which I will be testing rest controller methods. Is it a good idea? Or should I somehow mock database, and not deleting records before all tests? RestControllerTest class:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = WebApplicationContextConfig.class)
@WebAppConfiguration
public class ItemControllerTest {
    @Autowired
    private WebApplicationContext webApplicationContext;

    @Autowired
    private ItemRepository itemRepository;

    private MockMvc mockMvc;

    private final List<Item> items = new ArrayList<>();

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        itemRepository.deleteRecords();

        Item item1 = new Item();
        item1.setItemId("1");
        item1.setName("Shirt A");
        item1.setCategory("Shirt");
        item1.setColor("Black");
        item1.setSize("XL");
        item1.setQuantity(15);
        item1.setArchived(false);
        items.add(item1);
        itemRepository.addItem(item1);

        Item item2 = new Item();
        item2.setItemId("2");
        item2.setName("Trousers D");
        item2.setCategory("Trousers");
        item2.setColor("Brown");
        item2.setSize("S");
        item2.setQuantity(12);
        item2.setArchived(true);
        items.add(item2);
        itemRepository.addItem(item2);

    }

    @Test
    public void shouldGetItems() throws Exception {
        mockMvc
                .perform(get("/items"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", hasSize(2)))
                .andExpect(jsonPath("$[0].itemId", is(items.get(0).getItemId())))
                .andExpect(jsonPath("$[0].name", is(items.get(0).getName())))
                .andExpect(jsonPath("$[0].category", is(items.get(0).getCategory())))
                .andExpect(jsonPath("$[0].color", is(items.get(0).getColor())))
                .andExpect(jsonPath("$[0].size", is(items.get(0).getSize())))
                .andExpect(jsonPath("$[0].quantity", is(items.get(0).getQuantity().intValue())))
                .andExpect(jsonPath("$[0].archived", is(items.get(0).isArchived())))
                .andExpect(jsonPath("$[1].itemId", is(items.get(1).getItemId())))
                .andExpect(jsonPath("$[1].name", is(items.get(1).getName())))
                .andExpect(jsonPath("$[1].category", is(items.get(1).getCategory())))
                .andExpect(jsonPath("$[1].color", is(items.get(1).getColor())))
                .andExpect(jsonPath("$[1].size", is(items.get(1).getSize())))
                .andExpect(jsonPath("$[1].quantity", is(items.get(1).getQuantity().intValue())))
                .andExpect(jsonPath("$[1].archived", is(items.get(1).isArchived())));
    }
}
cerbin
  • 1,180
  • 15
  • 31

0 Answers0