java - 为什么新线程在事务性 Spring JUnit 测试中看不到主线程准备的测试数据?

标签 java spring spring-boot junit spring-test

我用Spring-boot-test写了一个Junit测试,在一个测试方法中,我先准备了一些测试数据,需要保存到MySQL DB中,然后调用目标方法,需要测试100个子方法线程来测试目标方法是否在并发中运行良好。该测试方法如下所示:

public class SysCodeRuleServiceImplTest extends BaseServiceTest {

    @Autowired
    private SysCodeRuleService sysCodeRuleService;

    @Autowired
    private SysCodeRuleDtlService sysCodeRuleDtlService;

    private final String codeRuleNo = "sdkfjks443";

        @Test
    public void testCreateSheetIdWithoutUniformedSerial_2() throws InterruptedException {
                //------ prepare test data start-----------
        SysCodeRule sysCodeRule = new SysCodeRule();
        sysCodeRule.setCodeRuleNo(codeRuleNo);
        sysCodeRule.setIfDateCode(1);
        sysCodeRule.setPadChar("0");
        sysCodeRule.setSerialDigits(6);
        sysCodeRule.setResetMode(1);
        sysCodeRule.setIfUniteSerial(0);
        sysCodeRule.setIfCache(0);
        sysCodeRule.setConstValue("PETREL");
        sysCodeRule.setStatus(1);
        sysCodeRule.setName(codeRuleNo);
        sysCodeRule.setCurSerialNo("0");
        sysCodeRule.setCurSerialDate(new Date());
        sysCodeRule.setCreateTime(new Date());
        sysCodeRule.setCreator("自动");
        sysCodeRule.setDateCutBeginPosition(3);
        sysCodeRule.setDateCutEndPosition(8);
        boolean insertSysCodeRuleSucc = sysCodeRuleService.insert(sysCodeRule);
        assertThat(TestMessageConstants.PREPARE_TEST_DATA_FAILED, insertSysCodeRuleSucc);
        assertThat("", sysCodeRule.getId(), notNullValue());

        SysCodeRuleDtl sysCodeRuleDtl1 = new SysCodeRuleDtl();
        sysCodeRuleDtl1.setSysCodeId(sysCodeRule.getId() + "");
        sysCodeRuleDtl1.setOrderNo(1);
        sysCodeRuleDtl1.setFieldValue("locno");
        sysCodeRuleDtl1.setCutEndPosition(0);
        sysCodeRuleDtl1.setCutBeginPosition(0);
        sysCodeRuleDtl1.setCreateTime(new Date());
        sysCodeRuleDtl1.setCreator("自动");
        boolean insertDtl1Succ = sysCodeRuleDtlService.insert(sysCodeRuleDtl1);
        assertThat("", insertDtl1Succ);

        SysCodeRuleDtl sysCodeRuleDtl2 = new SysCodeRuleDtl();
        sysCodeRuleDtl2.setSysCodeId(sysCodeRule.getId() + "");
        sysCodeRuleDtl2.setOrderNo(2);
        sysCodeRuleDtl2.setFieldValue("fieldName1");
        sysCodeRuleDtl2.setCutBeginPosition(1);
        sysCodeRuleDtl2.setCutEndPosition(3);
        sysCodeRuleDtl2.setCreateTime(new Date());
        sysCodeRuleDtl2.setCreator("自动");
        boolean insertDtl1Succ2 = sysCodeRuleDtlService.insert(sysCodeRuleDtl2);
        assertThat("", insertDtl1Succ2);
                //------prepare test data end------------------------

                //startLatch used to make sure all task threads start after 
                //prepared test data done
        CountDownLatch startLatch = new CountDownLatch(1);
                //parameters needed by the target method
        Map<String, String> fieldValueMap = new HashMap<>(2);
        fieldValueMap.put("locno", "cangku1");
        fieldValueMap.put("fieldName1", "ABCDEFGH");
                //doneLatch used to make sure all task threads done before the
                //the transaction which started in main thread roll back
        CountDownLatch doneLatch = new CountDownLatch(100);
        for(int i = 0; i < 100; i++) {
            new Thread(() -> {
                try {
                    startLatch.await();
                //this is the target method which i want to test
                    String result = sysCodeRuleService.createSheetIdWithoutUniformedSerial(codeRuleNo, JsonUtils.writeValueAsString(fieldValueMap));
                    if(CommonUtil.isNotNull(result)) {
                        logger.debug(">>>>>>>>>>>>>" + result);
                    }
                } catch(InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    doneLatch.countDown();
                }
            }).start();
        }

                //guarantee the test data truly saved before all task treads 
                //start
        EntityWrapper<SysCodeRule> ew = new EntityWrapper<>();
        ew.eq("code_rule_no", codeRuleNo);
        SysCodeRule codeRule = sysCodeRuleService.selectOne(ew);
        if(codeRule != null) {
            startLatch.countDown();
        }
                //main thread keep waiting until all task threads done their 
                //work
        doneLatch.await();
    }

BaseServiceTest 看起来像这样:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = TestApplication.class)
@Transactional
@Rollback
public class BaseServiceTest {
    protected  Logger logger = LoggerFactory.getLogger(BaseServiceTest.class);
}

目标方法的签名如下所示:

public synchronized String createSheetIdWithoutUniformedSerial(String codeRuleNo, String fieldValuesJson)

在目标方法中,它查询“准备测试数据”代码块保存的数据,然后执行一些业务逻辑代码,然后返回结果。 顺便说一下,在“业务服务层”中写的目标方法有Spring AOP管理的事务,事务配置文件如下所示:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="doReweight" propagation="REQUIRES_NEW"/>
            <tx:method name="doClear*" propagation="REQUIRES_NEW"/>
            <tx:method name="doSend*" propagation="REQUIRES_NEW"/>
            <tx:method name="doBatchSave*" propagation="REQUIRES_NEW"/>

            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="count*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="find*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="list*" propagation="REQUIRED" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>

    <aop:config expose-proxy="true" proxy-target-class="true">
        <aop:pointcut id="txPointcut"
                      expression="execution(* com.xxx..service..*+.*(..))"/>
        <aop:advisor id="txAdvisor" advice-ref="txAdvice"
                     pointcut-ref="txPointcut"/>
    </aop:config>
</beans>

我的预期结果是同步目标方法运行良好

但是!在每个子任务线程中,目标方法无法查询出在主线程中准备好的测试数据!

所以,我很困惑,无法弄清楚哪里出了问题?需要一些帮助或提示,非常感谢你们的帮助,提前致谢!

ps:spring-boot版本为:1.5.10.RELEASE,Juite版本为:4.12

最佳答案

通过您的 SysCodeRuleService 与数据库的初始交互将测试数据插入未提交给数据库的测试管理事务中。

在您的 SysCodeRuleService 上调用 createSheetIdWithoutUniformedSerial() 然后在一个新线程中执行;但是,Spring 不会将事务传播到新生成的线程。因此,createSheetIdWithoutUniformedSerial() 的调用在另一个线程中运行,该线程看不到挂起的测试管理事务中未提交的测试数据。

为了允许 createSheetIdWithoutUniformedSerial() 在新线程中查看数据库中的此类测试数据,您必须在生成任何新线程之前将测试数据提交到数据库。

实现这一点有多种选择。

如果您正在寻找一种非常低级的技术,您可以使用 Spring's TransactionTemplate以编程方式提交给数据库。这甚至应该与适当的测试管理事务一起工作(即,通过测试类或测试方法上的 @Transactional)。

如果您想执行特定于当前 @Test 方法的数据库设置,另一种选择是使用 TestTransaction API。参见 Programmatic Transaction Management在 Spring 框架引用手册中了解详细信息。

如果要对当前类中的所有测试方法执行相同的数据库设置,可以引入一个将测试数据插入数据库的@BeforeTransaction方法和一个@AfterTransaction 从数据库中删除测试数据的方法。参见 Running Code Outside of a Transaction .

如果您愿意或有兴趣将您的测试数据设置移动到 SQL 插入语句(可能在外部文件中),您可以使用 Spring's @Sql support .

作为旁注,您可以安全地删除 @Rollback 声明,因为您正在使用默认语义有效地覆盖默认语义。

关于java - 为什么新线程在事务性 Spring JUnit 测试中看不到主线程准备的测试数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54701838/

相关文章:

java - 如何更快地在 Java 中创建/复制对象?

java - 理解基本递归

java - Redis 问题考虑在您的配置中定义类型为 'org.springframework.data.redis.core.HashOperations' 的 bean

docker - 每次spring boot启动时ElasticSearch健康检查失败

java - Spring Boot 2 没有序列化 LocalDateTime

java - 在 Java 中使用对象的副本

java - dom4j:如何解决此 XPath 错误?

java - Spring Boot 2(Spring Batch 应用程序)无法启动。失败并出现 BeanCreationException : Error creating bean with name 'h2Console'

spring - Spring 数据中的标准

javax.imageio.IIOException : I/O error writing PNG file 异常