簡體   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