重置 H2 增量器

问题描述 投票:0回答:1

如何重置H2中的id增量器?如果你愿意的话,可以将其称为 XY 问题,但我的测试失败只是因为 ids (

GenerationType.IDENTITY
) 不匹配。我清除了
@BeforeEach
中的行,但增量器未重置,因此出现错误

package pp.spring_bootstrap.dao;

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.context.SpringBootTest;
import pp.spring_bootstrap.models.Role;

import java.util.List;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

@SpringBootTest
class RoleDaoTest {
    @Autowired
    RoleDao roleDao;
    static final Role USER = new Role("USER");
    static final Role ADMIN = new Role("ADMIN");
    @BeforeEach
    void addSampleRows() {
        roleDao.saveAll(List.of(USER, ADMIN));
    }
    @AfterEach
    void clearRows() {
        roleDao.deleteAll();
    }
    @Test
    void findByAuthority() {
        assertThat(roleDao.findByAuthority("USER")).isEqualTo(USER);
    }

    @Test
    void findByAuthorityOrAuthority() {
        assertThat(roleDao.findByAuthorityOrAuthority("USER", "ADMIN")).asList().contains(USER, ADMIN);
    }
}
package pp.spring_bootstrap.models;

import jakarta.persistence.*;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import org.springframework.security.core.GrantedAuthority;

import java.util.Set;
import java.util.StringJoiner;

@Entity
@Table(name = "roles")
@Getter
@Setter
@EqualsAndHashCode
public class Role implements GrantedAuthority {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long id;
    @Column(name = "role", nullable = false, unique = true)
    private String authority;
    @ManyToMany(mappedBy = "authorities")
    @EqualsAndHashCode.Exclude
    private Set<User> userList;

    public Role() {
    }

    public Role(String authority) {
        this.authority = authority;
    }

    @Override
    public String getAuthority() {
        return authority;
    }

    // toString()
}
java.lang.AssertionError: 
Expecting ArrayList:
  [Role[id=4, role='ADMIN'], Role[id=3, role='USER']]
to contain:
  [Role[id=1, role='USER'], Role[id=2, role='ADMIN']]
but could not find the following element(s):
  [Role[id=1, role='USER'], Role[id=2, role='ADMIN']]

GPT 建议

@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_EACH_TEST_METHOD)
,但它会大大减慢测试速度。每次为了这些 id 匹配而重新创建上下文似乎有点过分了

java spring-boot testing h2 spring-test
1个回答
0
投票

仅测试

authority
Role
,而不是整个对象。

@Test
void findByAuthorityOrAuthority() {
    assertThat(roleDao.findByAuthorityOrAuthority("USER", "ADMIN"))
        .stream()
        .map(Role::getAuthority)
        .collect(Collectors.toList())
        .contains("USER", "ADMIN");
}

建议在

findByAuthority
测试中进行类似的更改,因为无法保证测试运行的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.