Donate. I desperately need donations to survive due to my health

Get paid by answering surveys Click here

Click here to donate

Remote/Work from Home jobs

Spring boot Rest Controller testing with h2 Embedded database

I have spring boot application with REST api. Inside REST API method call Spring service method and it called Spring JPA method.

@RestController
public class Test{

     @Autowired
     private TestService service;

     @RequestMapping(path = "/add", method = RequestMethod.POST)
     public void add() {
          service.add();
     }
}


@Service
public class TestService{

    @Autowired
    private TestRepository repository;    

    public void add() {
         repository.save();
    }
}

TestrRepository save method save data to sql database.

@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@AutoConfigureMockMvc
public class UnitTest {

    @Autowired
    private WebApplicationContext webApplicationContext;

    private MockMvc mockMvc;


    @Before
    public void init() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void login() throws Exception {

        MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.post("/add")).andReturn();

        int status = mvcResult.getResponse().getStatus();

        System.out.println(status");
    }
}

mvn test command execute without errors , but status code every time return 404.

What is the reason for this and how I fox this.

Comments