Spring boot test @Transactional not saving

后端 未结 5 1380
别那么骄傲
别那么骄傲 2020-12-17 21:24

I\'am trying to do a simple Integration test using Spring Boot Test in order to test the e2e use case. My test does not work because I\'am not able to make the repository sa

5条回答
  •  感情败类
    2020-12-17 22:21

    Thanks to M. Deinum, I think I get the point, So the best is to separate the logic of the test into two tests, the first will testing just the service (so this one could be transactional) and the second the controller:

    Test 1:

    @Test
    @Transactional
    public void testServiceSaveAndRead() {
        personService.createPerson(1, "person1");
        Assert.assertTrue(personService.getPersons().size() == 1);
    }
    

    Test 2:

    @MockBean
    private PersonService personService;
    
    @Before
    public void setUp() {
        //mock the service
        given(personService.getPersons())
                .willReturn(Collections.singletonList(new Person(1, "p1")));
    }
    
    @Test
    public void testController() {
        ResponseEntity persons = restTemplate.getForEntity("/persons", Person[].class);
        Assert.assertTrue(persons.getBody()!=null && persons.getBody().length == 1);
    }
    

    Hope that it will help someone someday ... thanks for all of you

提交回复
热议问题