Search code examples
mysqlnullpointerexceptionpersistencedaodbunit

"java.lang.NullPointerException" error in my generic Dao while configuring unitary testing with DBUnit


I receive the "java.lang.NullPointerException" error in the following line:

miIdioma=miDao.find(Idioma.class, "playa");

miIdioma is an object from de class "Idioma" which is composed by the atrributes "palabra" and "idioma"

The Dao file is called IIdiomaDao.java and I would like to use its method:

public <T> T find(Class<T> clazz, Serializable id) {
        return entityManager.find(clazz, id);
    }

To gain access to this method I declared the variable miDao in the original file

private IIdiomaDao miDao;

Finally, I am using this method to gain access

miIdioma=miDao.find(Idioma.class, "playa");

I understood that this error is shown when a variable is not initialized, but I connected the database to my projects and the database data is supposed to be uploaded. To performed the unitary testing I followed these steps:

  1. I connected the database

    public class IdiomaDaoTest {
    
      private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
      private static final String JDBC_URL = "jdbc:mysql://localhost:3306/diccionario";
      private static final String USER = "root";
      private static final String PASSWORD = "mypassword";
    

    }

  2. I imported and red data

Blockquote

public void importDataSet() throws Exception {
      IDataSet dataSet = readDataSet();
      cleanlyInsert(dataSet);
  }

  private IDataSet readDataSet() throws Exception {
      return new FlatXmlDataSetBuilder().build(new File("/home/inta/workspace/JPAconPruebasUnitarias/src/test/sources/FlatXmlDataSet.xml"));
  }

  private void cleanlyInsert(IDataSet dataSet){
      IDatabaseTester databaseTester;
    try {
        databaseTester = new JdbcDatabaseTester(JDBC_DRIVER, JDBC_URL, USER, PASSWORD);
        databaseTester.setSetUpOperation(DatabaseOperation.CLEAN_INSERT);
        databaseTester.setDataSet(dataSet);
        databaseTester.onSetup();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  }

Note1: Here, I suppose that the database has been uploaded and therefore initialized it.

My question is: Why miDao is pointing Null? What am I doing wrong?

Note2: my dataset is:

<!DOCTYPE dataset SYSTEM "my-dataset.dtd" >
<dataset>
    <idioma palabra="playa" idioma="español"/>
    <idioma palabra="beach" idioma="ingles"/>
    <idioma palabra="platja" idioma="catalan"/>
</dataset>

Thank you very much, this community rocks!


Solution

  • Issue is here.

    private IIdiomaDao miDao;// you have declare the miDao
    

    But not initialize it.

    Then You will get NullPointerException here

    miIdioma=miDao.find(Idioma.class, "playa"); // NullPointerException since
                                                // miDao is null
    

    Initialize miDao to avoid NullPointerException