在springboot中完成测试后截断h2表

问题描述

在JUnit类中完成一项测试后,我试图清理h2表,但是它抛出错误。 我已经用@Sql注释对测试类进行了注释,以运行一些初始脚本,这些脚本需要在JUnit完成时进行清理。但是在完成期间,truncate语句将失败。

在这里例外

org.springframework.jdbc.datasource.init.ScriptStatementFailedException: Failed to execute SQL script statement #1 of Byte array resource [from inlined SQL statement: TRUNCATE TABLE con_tag;]: TRUNCATE TABLE con_tag; nested exception is org.h2.jdbc.JdbcSQLSyntaxErrorException: Cannot truncate "PUBLIC.CON_TAG"; SQL statement:
TRUNCATE TABLE con_tag [90106-200]
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:622)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.populate(ResourceDatabasePopulator.java:254)
    at org.springframework.jdbc.datasource.init.DatabasePopulatorUtils.execute(DatabasePopulatorUtils.java:49)
    at org.springframework.jdbc.datasource.init.ResourceDatabasePopulator.execute(ResourceDatabasePopulator.java:269)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$4(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.transaction.support.TransactionOperations.lambda$executeWithoutResult$0(TransactionOperations.java:68)
    at org.springframework.transaction.support.TransactionTemplate.execute(TransactionTemplate.java:140)
    at org.springframework.transaction.support.TransactionOperations.executeWithoutResult(TransactionOperations.java:67)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:263)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.lambda$executeSqlScripts$0(SqlScriptsTestExecutionListener.java:185)
    at java.base/java.lang.Iterable.forEach(Iterable.java:75)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:185)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.executeSqlScripts(SqlScriptsTestExecutionListener.java:147)
    at org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener.afterTestMethod(SqlScriptsTestExecutionListener.java:126)
    at org.springframework.test.context.TestContextManager.afterTestMethod(TestContextManager.java:441)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:94)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
    at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:115)
    at org.junit.vintage.engine.execution.RunnerExecutor.execute(RunnerExecutor.java:43)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.accept(ForEachOps.java:183)
    at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:195)
    at java.base/java.util.Iterator.forEachRemaining(Iterator.java:133)
    at java.base/java.util.Spliterators$IteratorSpliterator.forEachRemaining(Spliterators.java:1801)
    at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:484)
    at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:474)
    at java.base/java.util.stream.ForEachOps$ForEachOp.evaluateSequential(ForEachOps.java:150)
    at java.base/java.util.stream.ForEachOps$ForEachOp$OfRef.evaluateSequential(ForEachOps.java:173)
    at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.base/java.util.stream.ReferencePipeline.forEach(ReferencePipeline.java:497)
    at org.junit.vintage.engine.VintageTestEngine.executeAllChildren(VintageTestEngine.java:82)
    at org.junit.vintage.engine.VintageTestEngine.execute(VintageTestEngine.java:73)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:248)
    at org.junit.platform.launcher.core.DefaultLauncher.lambda$execute$5(DefaultLauncher.java:211)
    at org.junit.platform.launcher.core.DefaultLauncher.withInterceptedStreams(DefaultLauncher.java:226)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:199)
    at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:141)
    at org.eclipse.jdt.internal.junit5.runner.JUnit5TestReference.run(JUnit5TestReference.java:98)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:542)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:770)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:464)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:210)
Caused by: org.h2.jdbc.JdbcSQLSyntaxErrorException: Cannot truncate "PUBLIC.CON_TAG"; SQL statement:
TRUNCATE TABLE con_tag [90106-200]
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:576)
    at org.h2.message.DbException.getJdbcSQLException(DbException.java:429)
    at org.h2.message.DbException.get(DbException.java:205)
    at org.h2.message.DbException.get(DbException.java:181)
    at org.h2.command.ddl.TruncateTable.update(TruncateTable.java:43)
    at org.h2.command.CommandContainer.update(CommandContainer.java:198)
    at org.h2.command.Command.executeUpdate(Command.java:251)
    at org.h2.jdbc.JdbcStatement.executeInternal(JdbcStatement.java:228)
    at org.h2.jdbc.JdbcStatement.execute(JdbcStatement.java:201)
    at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95)
    at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java)
    at org.springframework.jdbc.datasource.init.ScriptUtils.executeSqlScript(ScriptUtils.java:601)
    ... 55 common frames omitted

这是测试类TagTxnTest.java

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.context.jdbc.Sql.ExecutionPhase;
import org.springframework.test.context.jdbc.SqlConfig;
import org.springframework.test.context.jdbc.SqlGroup;
import org.springframework.test.context.jdbc.SqlConfig.TransactionMode;
import org.springframework.test.context.junit4.SpringRunner;

import com.mypleaks.config.TestRedisConfiguration;
import com.mypleaks.constant.PleaksConstants;
import com.mypleaks.model.dto.Tag;
import com.mypleaks.model.dto.User;
import com.mypleaks.model.flat.FlatCountry;
import com.mypleaks.model.request.ReqTag;
import com.mypleaks.service.UserService;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestRedisConfiguration.class)
@SqlGroup({
@Sql(executionPhase = ExecutionPhase.BEFORE_TEST_METHOD,config = @SqlConfig(transactionMode = TransactionMode.ISOLATED),scripts = { "classpath:/sql/users.sql","classpath:/sql/locations.sql","classpath:/sql/tags.sql" }),@Sql(executionPhase = ExecutionPhase.AFTER_TEST_METHOD,statements = { "TRUNCATE TABLE con_tag_eval;","TRUNCATE TABLE con_tag;","TRUNCATE TABLE us_role;","TRUNCATE TABLE us_user;","TRUNCATE TABLE rd_place;","TRUNCATE TABLE rd_region;","TRUNCATE TABLE rd_country" })})
public class TagTxnTest {

    @Autowired
    private TagTxn tagTxn;

    @Autowired
    private UserService userService;

    @Test
    public void createTagWithAllActiveCountriesTest() {
        User user = userService.getProfileByEmailId("xxxxxxx@gmail.com");
        ReqTag reqTag = new ReqTag("India-China");
        reqTag.setIp(PleaksConstants.PROVIDER_IP);
        final Tag saved = tagTxn.createTag(user,reqTag);
        assertNotNull(saved);
    }

    @Test
    public void createTagWithRequestedCountriesTest() {
        List<FlatCountry> countries = new ArrayList<FlatCountry>();
        countries.add(new FlatCountry(1l));
        countries.add(new FlatCountry(3l));
        countries.add(new FlatCountry(8l));
        User user = userService.getProfileByEmailId("xxxxxxx@gmail.com");
        ReqTag reqTag = new ReqTag("India-China");
        reqTag.setCountries(countries);
        reqTag.setIp(PleaksConstants.PROVIDER_IP);
        final Tag saved = tagTxn.createTag(user,reqTag);
        assertNotNull(saved);
    }
}

这是主要班级

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.mypleaks.constant.PleaksIndicator;
import com.mypleaks.model.dto.Place;
import com.mypleaks.model.dto.Tag;
import com.mypleaks.model.dto.TagEvaluation;
import com.mypleaks.model.dto.User;
import com.mypleaks.model.request.ReqTag;
import com.mypleaks.repo.content.TagDAO;
import com.mypleaks.service.EvaluationService;
import com.mypleaks.service.PlaceService;

@Repository
public class TagTxn {

    @Autowired
    private TagDAO tagDAO;

    @Autowired
    private PlaceService placeService;

    @Autowired
    private EvaluationService evaluationService;

    @Transactional
    public Tag createTag(User user,ReqTag reqTag) {
        Tag userTag = new Tag(user,PleaksIndicator.USER_TAG,reqTag.getName(),reqTag.getIp(),PleaksIndicator.ACTIVE);
        userTag.setTagable(true);
        userTag = tagDAO.save(userTag);
        long tagId = userTag.getId();
        List<TagEvaluation> tagEvaluations = new ArrayList<TagEvaluation>();
        Map<Long,Place> countryCapitalMap = placeService.getActiveCountryCapitalMap();
        if (reqTag.getCountries() != null && !reqTag.getCountries().isEmpty()) {
            reqTag.getCountries().forEach(country -> {
                if (countryCapitalMap.get(country.getCountryId()) != null) {
                    tagEvaluations.add(new TagEvaluation(tagId,country.getCountryId()));
                }
            });
        } else {
            countryCapitalMap.values().forEach(place -> {
                tagEvaluations.add(new TagEvaluation(tagId,place.getCountryId()));
            });
        }
        userTag.setTagEvaluations(evaluationService.saveAllTagEvaluation(tagEvaluations));
        return userTag;
    }
}

有人可以建议我为什么会遇到这个异常。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...