简体   繁体   English

Junit 用于@Transactional

[英]Junit for @Transactional

I need to write a test which shows that my transaction is triggering.我需要编写一个测试来表明我的事务正在触发。

ClientDAOImpl.java - file with a transcational methods. ClientDAOImpl.java - 带有事务方法的文件。

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class ClientDAOImpl implements ClientDAO {

    private final Connection  conn;
    private PreparedStatement st;
    private ResultSet         rs;

    public ClientDAOImpl() throws SQLException, ClassNotFoundException {
        this.conn = new PostgresConnection().createConnection();
    }

    @Override
    public User get(final long id) throws SQLException {

        User client = null;
        this.st = this.conn.prepareStatement("SELECT * FROM CUSTOMERS WHERE sid = ?;");
        this.st.setLong(1, id);
        this.rs = this.st.executeQuery();
        while (this.rs.next()) {
            this.rs.getLong("sid");

            //some code

            client = new User(FIRST_NAME, LAST_NAME, PHONE_NUMBER, EMAIL, CARD_NUMBER,
                    DELIVERY_ADDRESS, COMMENT);
        }
        DAO.closing(this.rs, this.st, this.conn);
        if (client == null) {
            System.out.println("Something wrong with getting client by id - " + id);
        } else {
            System.out.println("Client with the id = " + id + " successfully retrieved");
        }
        return client;

    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS, readOnly = false)
    public int insert(final User user) throws SQLException, ClassNotFoundException {
        this.st = this.conn.prepareStatement(
                "INSERT INTO CUSTOMERS(FIRST_NAME,LAST_NAME,PHONE_NUMBER,EMAIL,CARD_NUMBER,DELIVERY_ADDRESS,COMMENT)VALUES(?,?,?,?,?,?,?);");
        
        //some code

        final int res = this.st.executeUpdate();
        System.out.println("User " + user + " successfully inserted");
        return res;
    }

}

MyTest.java - file with my test MyTest.java - 我的测试文件

@ContextConfiguration(classes = Store.class, locations = {"classpath*:beans.xml"})
@RunWith(SpringRunner.class)
@WebMvcTest(MainApp.class)
@Transactional
@Rollback(true)
@TestExecutionListeners({TransactionalTestExecutionListener.class})
public class StoreTest {

    private LocalValidatorFactoryBean localValidatorFactory;
    @MockBean
    HttpRequest                       request;
    HttpRequest                       response;

    @MockBean
    private User                      user;
    @Mock
    private Model                     model;
    @Autowired
    MockMvc                           mockMvc;

    @Mock
    Store                             store;

    @Autowired
    List<Products>                    products;

    @Before
    public void setup() {

        this.localValidatorFactory = new LocalValidatorFactoryBean();
        this.localValidatorFactory.setProviderClass(HibernateValidator.class);
        this.localValidatorFactory.afterPropertiesSet();

        MockitoAnnotations.initMocks(this);
        final Store store = new Store(this.products);

        this.mockMvc = MockMvcBuilders.standaloneSetup(store).build();

    }

    @Test
    public void testForTransaction() throws ClassNotFoundException, SQLException {
        final User user = new User();
        user.setFirstName("Ivan");
        user.setLastName("Ivanov");
        user.setPhoneNumber("18000000");
        user.setEmail("mail@gmail.com");
        user.setCardNumber("4111111111111111");
        user.setDeliveryAddress("address");
        user.setComment("comment");

        String result = "";

        try {
            final Connection connection = new PostgresConnection().createConnection();
            if (connection != null) {
                System.out.println("Success");
            }
            final ClientDAO clientDao = new ClientDAOImpl();
            clientDao.insert(user);

            result = clientDao.get(3L).getFirstName();
        } finally {
        }

        Assert.assertEquals("it should be equal", "Ivan", result);
    }

And my test is successful and i'm getting this:我的测试成功了,我得到了这个:

User my.app.entities.User@2e5ee2c9 successfully inserted
Client with the id = 3 successfully retrieved
Rolled back transaction for test context [DefaultTestContext@7103ab0 testClass = StoreTest,...// and etc

So my question is how to write a correct test for my example and to show that my transaction is working?所以我的问题是如何为我的示例编写正确的测试并表明我的事务正在运行?

I don't think that one needs to test whether transactions are working or not.我认为不需要测试交易是否有效。 Hibernate provides you with annotation @Transactional, which is already well tested and proofed to work correctly, that means that you can be sure about your transaction is working if you have put @Transactional annotations in desired places (on classes, interfaces or methods) which is the case for you. Hibernate 为您提供注解@Transactional,它已经过良好的测试和证明可以正常工作,这意味着如果您将@Transactional 注解放在所需的位置(在类、接口或方法上),您可以确定您的事务正在工作。是你的情况。 If you want to test your data being stored in real DB and then fetched correctly you should refer to integration or full testing techniques, also refer to h2 databases which are embedded databases used mostly for tests of this kind.如果您想测试存储在真实数据库中然后正确获取的数据,您应该参考集成或完整测试技术,也可以参考 h2 数据库,它们是主要用于此类测试的嵌入式数据库。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM