어떻게 내 Junit와의 모든 새 트랜잭션에 대한 내 SQL 데이터를 사용할 수 있도록하기 위해?

DarkCrow :

나는 JUnit 테스트 케이스를 만들려고 해요. 내가 생성하고 새로운 트랜잭션의 엔티티를 저장 내 프로세서 메서드에서 호출되는 만드는 방법이있다. 문제는 내가 내 SQL에로드하고있어 그 데이터는 새로운 트랜잭션을 사용할 수 없습니다입니다.

프로세서 방법 :

public void updateFoo(final Test test) throws ProcessingException {
        //Business logics
        Foo foo = this.fooHelper.createAndSaveFoo(test);
        //other business logics
        foo.setName ("Name");
        ...
        ...
    }

도우미 방법 :

@Transactional(propagation = Propagation.REQUIRES_NEW)
    public Foo createAndSaveFoo(final Test test) throws NotFoundException, BadRequestException {
        if (this.isFooPresent(test)) {
            throw new BadRequestException(LOGGER, "CANNOT_CREATE_FOO", "Foo already created for the test");
        }
        final Foo foo = this.fooDAO.save(this.fooFactory.createFoo(test));
        LOGGER.debug("Foo is saved successfully!, Entity@@ {}", foo);
        return foo;
    }

공장 방법 :

public Foo createFoo(final Test test) throws NotFoundException {
     return Foo.FooBuilder.aFoo().
                        withId(test.getId()).
                        withDate((test.getDate()).
                        withSize(test.getSize()).
                        withType(getType(test.getTypeId()).
                        build();
            }

    private Type getType(final int id) throws NotFoundException {
      return this.typeDAO.findById(id).orElseThrow(() -> new NotFoundException(LOGGER, TYPE_NOT_FOUND, "Invalid type id"));
    }

실재:

@Entity
@Table(name = "foo")
public class Foo {

    @Column(name = "id")
    private Long id;

    @Column(name = "date")
    private Date date;

    @Column(name = "size")
    private Long size;

    @ManyToOne
    @JoinColumn(name = "type", foreignKey = @ForeignKey(name = "fk__foo__type_id"))
    private Type type;

    //getters, setters and builders

}

@Entity
@Table(name = "type")
public class Type {

    @Column(name = "id")
    private Long id;

    @Column(name = "date")
    private String name;


    //getters and setters

}

실험 방법:

@Test
@Transactional
@Sql(value = {"classpath:sql/create_foo_data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
@Sql(value = {"classpath:sql/clean_everything.sql"}, executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
public void foo_test() throws ProcessingException {

        //GIVEN
        Test test = new Test();
        test.setId(12);
        test.setDate(new Date());
        test.setSize(20);
        test.setTypeId(1);

        // WHEN
        this.fooProcessor.updateFoo(test);

        // THEN
        final List<Foo> foo = this.fooDAO.findAll();
        assertEquals(1, foo.size());
        assertEquals(20, foo.get(0).getSize());
        assertEquals("Test2", foo.get(0).getType().getName());


    }

foo_data.sql

INSERT INTO `type` (`id`, `name`) VALUES (0, 'Test1'), (1, 'Test2');

로그 :

com.deep.common.core.exception.NotFoundException:  errorCode: 'TYPE_NOT_FOUND' - errorMessage : 'Invalid type id'
    at com.deep.process.factory.entity.FooFactory.lambda$createFoo$0(FooFactory.java:55)
    at java.util.Optional.orElseThrow(Optional.java:290)

내 SQL에서 유형을 삽입 한 경우에도 그 ()는 createAndSaveFoo로 자궁강 새 트랜잭션을 생성하지 않았습니다. 어떻게 SQL 데이터는 새로운 트랜잭션에 사용할 수 있습니까?

조엘 :

당신은 설정을 명시 적으로 시도 transactionModeISOLATED당신의 내 @sql주석? 그게 당신의 시험 방법이 실행되기 전에 삽입이 최선을 다하고 있습니다 있도록하는 데 도움이 될 수 있습니다. IE

@Sql(value = {"classpath:sql/create_foo_data.sql"}, executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, config = @SqlConfig(transactionMode = SqlConfig.TransactionMode.ISOLATED))

추천

출처http://43.154.161.224:23101/article/api/json?id=25493&siteId=1