简体   繁体   中英

Junit for @Transactional

I need to write a test which shows that my transaction is triggering.

ClientDAOImpl.java - file with a transcational methods.

@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

@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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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