TransWikia.com

Is it possible to test a java-based CRUD without using Spring Boot JPA?

Stack Overflow Asked by Caio Guedes on December 1, 2021

I’m studying Java and trying to code some tests with JUnit, but every tutorial or video that I find on YouTube uses Spring Boot JPA. I don’t want to "skip steps" by trying to set up it right now ’cause I’ve never studied it before and it seems complicated. There is any way to create some JUnit tests without using it or it is mandatory to test a CRUD?

For example, this is the code that I’m trying to test:

public void save(User user) {
    //inserindo parsing para que os parâmetros inseridos substituam as interrogações
    String sql = "INSERT INTO users(nome, dataNascimento, sexo) VALUES (?, ?, ?)"; 
    
    Connection conn = null;
    PreparedStatement pstm = null;//preparação da estrutura de execução do java com o SQL
    
    try {
        //cria uma conexão com o banco de dados
        conn = (Connection) ConnectionFactory.createConnectionToMySQL();
        
        pstm = conn.prepareStatement(sql);//executa uma query
        //passando os valores esperados pela query
        pstm.setString(1, user.getNome());
        pstm.setString(2, user.getDataNascimento());
        pstm.setString(3, user.getSexo());
        
        
        pstm.execute();
        
        System.out.println("Usuário inserido com sucesso na base de dados.");
    }catch (Exception e) {
        e.printStackTrace();
    }finally {
        
        //fechando conexões
        try {
            if(pstm!=null) {
                pstm.close();
            }
            
            if(conn!=null) {
                conn.close();
            }
        }catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

This is the repository link if needed:

https://github.com/caiocguedes/crud-neurotech

Thanks in advance.

One Answer

You don't need Spring for Java JDBC and you don't need to test CRUD since DAO layer (CRUD) is usually not tested.

Here is a tutorial for Java JDBC

https://javamondays.com/simple-java-jdbc-example/

Answered by J Asgarov on December 1, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP