测试在单独运行时通过,但在运行整个类时不通过

n53p2ov0  于 2022-10-23  发布在  Spring
关注(0)|答案(1)|浏览(173)

当我单独运行测试时,每个人都认为没问题,但当我运行整个测试类时,我在我运行的3个方法中得到了这个3异常,它是:getPersonById/savePerson/deleteById。RESTEST方法运行成功
GetPersonByID方法:
Java.util.NoSuchElementException:不存在值

SavePerson方法:
异常:找不到ID为%1的com.entity.Person

DeleteByID方法:
Org.springframework.dao.EmptyResultDataAccessException:不存在ID为%1的com.entity.Person类实体!
代码:

package com.repository;

import com.entity.Person;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;

import java.util.List;
import java.util.Optional;

import static org.junit.jupiter.api.Assertions.*;

@DataJpaTest
class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository;

    private Person person;

    @BeforeEach
    public void setUp() {
        person = new Person();

        person.setId(1L);
        person.setName("Test1");
        person.setSurname("Test1_2");
        person.setDate_of_birth("18 Years");

    }

    @AfterEach
     void tearDown() {
        personRepository.deleteAll();
    }

    @Test
    public void shouldCheckIfPersonExists(){

        personRepository.save(person);
        assertTrue(personRepository.existsById(1L));

    }

    @Test
    public void getAllPerson() {

        personRepository.save(person);
        List<Person> list = personRepository.findAll();
        assertEquals(1, list.size());

    }

    @Test
        public void getPersonById() {

        personRepository.save(person);

        Optional<Person> byId = personRepository.findById(1L);

        assertEquals(person.getId(), byId.get().getId());
        assertEquals(person.getName(), byId.get().getName());

    }

    @Test
    public void savePerson() {

        personRepository.save(person);
        Person newPerson = personRepository.getById(1L);

        assertEquals(person.toString(), newPerson.toString());

    }

    @Test
    public void deleteById() {

        personRepository.save(person);
        personRepository.deleteById(1L);
        assertFalse(personRepository.existsById(1L));

    }

}
luaexgnf

luaexgnf1#

它可能会失败,因为您使用的save()方法并不是要保存具有ID集的实体。此方法自动生成ID,这就是它不总是为1的原因。

相关问题