0

I have one repository class which which implements CrudRepository. Then in service class I have auto wired this repositary. Then in controller class I have autowired this service.

I want to write test cases of controller Class. I am using below configuration.

    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
    public class XYZControllerTest {

        MockMvc mockMvc;

        @Mock
        private XYZController xyzController;

        @Autowired
        private TestRestTemplate template;

        @Autowired
        XYZRepository xyzRepository;

        @Before
        public void setup() throws Exception {
            mockMvc = MockMvcBuilders.standaloneSetup(xyzController).build();
        }

        @Test
        public void testPanelShouldBeRegistered() throws Exception {
            HttpEntity<Object> xyz = getHttpEntity("{\"name\": \"test 1\", \"email\": \"test10000000000001@gmail.com\","
                    + " \"registrationNumber\": \"41DCT\",\"registrationDate\":\"2018-08-08T12:12:12\" }");
            ResponseEntity<XYZ> response = template.postForEntity("/api/xyz", xyz, XYZ.class);

    }
}

My problem is that when I run test case, data is going to insert in DB which is used for application. Can I test it without inserting data in DB.

Dhaval Goti
  • 447
  • 2
  • 10
  • 25

1 Answers1

0

Conceptually when we are testing services we mock repositories instead of injection.

You need to mock your repository and setup behavior for returning data.

An example :

@MockBean
XYZRepository xyzRepository;

@Test
public void test() {

    // other mocks
    //
    when(xyzRepository.findAll()).thenReturn(Arrays.asList(new XYZ()));

    // service calls
    // assertions
}
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25