繁体   English   中英

Junit 用于@Transactional

[英]Junit for @Transactional

我需要编写一个测试来表明我的事务正在触发。

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 - 我的测试文件

@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);
    }

我的测试成功了,我得到了这个:

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

所以我的问题是如何为我的示例编写正确的测试并表明我的事务正在运行?

我认为不需要测试交易是否有效。 Hibernate 为您提供注解@Transactional,它已经过良好的测试和证明可以正常工作,这意味着如果您将@Transactional 注解放在所需的位置(在类、接口或方法上),您可以确定您的事务正在工作。是你的情况。 如果您想测试存储在真实数据库中然后正确获取的数据,您应该参考集成或完整测试技术,也可以参考 h2 数据库,它们是主要用于此类测试的嵌入式数据库。

暂无
暂无

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

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