简体   繁体   English

测试和控制器中标记为事务的方法的不同行为

[英]different behavior of method marked transactional in test and in controller

I have class CandidateService marked as @Transactional 我将CandidateService类标记为@Transactional

@Transactional
@Service("candidateService")
public class CandidateService {

    @Autowired
    private CandidateDao candidateDao;

    ....

    public void add(Candidate candidate) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String login = auth.getName();
        User user =  utilService.getOrSaveUser(login);
        candidate.setAuthor(user);
        candidateDao.add(candidate);
    }
   ...
}

dao implementation: dao实现:

@Override
    public Integer add(Candidate candidate) throws HibernateException{
        Session session = sessionFactory.getCurrentSession();
        if (candidate == null) {
            return null;
        }
        Integer id = (Integer) session.save(candidate);
        return id;

    }

if I write in @controller class: 如果我在@controller类中编写:

@RequestMapping("/submitFormAdd")
    public ModelAndView submitFormAdd(
            Model model,
            @ModelAttribute("myCandidate") @Valid Candidate myCandidate,
            BindingResult result,
            RedirectAttributes redirectAttributes) {
        if (result.hasErrors()) {
            return new ModelAndView("candidateDetailsAdd");
        }

        myCandidate.setDate(new Date());
        candidateService.add(myCandidate);

    .....
    }

After executing this methods data put to database! 执行此方法后,数据将存入数据库!

if I write test: 如果我写测试:

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"})
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests{

    @Autowired
    CandidateService candidateService;

    @BeforeClass
    public static void initialize() throws Exception{

        UtilMethods.createTestDb();

    }
    @Before
    public void setup() {
        TestingAuthenticationToken testToken = new TestingAuthenticationToken("testUser", "");
        SecurityContextHolder.getContext().setAuthentication(testToken);
    }

    @After
    public void cleanUp() {
        SecurityContextHolder.clearContext();
    }
    @Test
    public void add(){
        Candidate candidate = new Candidate();
        candidate.setName("testUser");
        candidate.setPhone("88888");
        candidateService.add(candidate);
        List<Candidate> candidates = candidateService.findByName(candidate.getName());
        Assert.assertNotNull(candidates);
        Assert.assertEquals("88888", candidates.get(0).getPhone());
    }
}

test is green but after executing I don't see data in my database. 测试为绿色,但是执行后,我在数据库中看不到数据。

Can you explain me why and how to fix it? 您能解释一下为什么以及如何解决吗?

UPDATE UPDATE

configuration:
<tx:annotation-driven transaction-manager="transactionManager" />

    <!-- Менеджер транзакций -->
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)

above your test class will not affect to database. 以上测试类不会影响数据库。

set or add defaultRollback = false to see data persisted in table. 设置或添加defaultRollback = false以查看表中defaultRollback = false数据。

我认为您应该使用参数defaultRollback = false添加TransactionConfiguration批注

After completion of test method the changes are rolled back. 测试方法完成后,更改将回滚。 Test method database changes are reverted and you can do the other test with new data. 测试方法数据库的更改将还原,您可以使用新数据进行其他测试。 You no need to worry about the model object with same id in different test cases. 您无需担心在不同的测试案例中具有相同ID的模型对象。

If you need common data you can do with in setup() method that changes also not saved in the database. 如果您需要通用数据,可以使用setup()方法处理,该更改也不会保存在数据库中。

Before executing test methods the setup() method will be called. 在执行测试方法之前,将调用setup()方法。 if you have 3 test method then 3 times setup() method will be called. 如果您有3种测试方法,则将调用3次setup()方法。

sorry for my bad English....... 对不起,我的英语不好.......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 事务注释的不同行为 - Transactional annotation different behavior @Transactional在控制器方法上不起作用 - @Transactional on controller method not working 标记为@Transactional的单元测试通过,但未标记为失败 - Unit test passes when marked @Transactional but fails when not 在@Transactional 测试期间了解@EntityListener 的行为 - understanding @EntityListener behavior during a @Transactional test 如何使用 @Transactional 注释测试方法 - How test a method with @Transactional annotation 使 spring 测试方法不是事务性的 - make spring test method NOT transactional io.micronaut.transaction.exceptions.NoTransactionException 在标有@Transactional 的方法中 - io.micronaut.transaction.exceptions.NoTransactionException in method marked with @Transactional 如何从@Transactional标记方法返回所有错误? - How to return all errors from an @Transactional marked method? 公共方法中的 LazyInitializationException 标记为 @Transactional 并从另一个 bean 调用 - LazyInitializationException in public method marked as @Transactional and called from another bean 当方法标记为 noRollback 时,@Transactional class 中的 UnexpectedRollbackException 抛出异常 - UnexpectedRollbackException in a @Transactional class when method is marked with noRollbackFor a thrown exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM