Ive got two classes. BatchDao, and BatchDaoImpl. BatchDao is an interface, and BatchDaoImpl contains the logic. You know the drill.
I am quite new to Spring, which presents a problem for me. How can I unit test the methods contained inside without using a container? Normally I would just write my methods as if they were just POJO's in JUnit and call it a day, as I did back in college.
However, I cant even get that far because my EntityManager(???) keeps giving me a NullPointerException, when I run my test in eclipse. I understand it has something to do with dependency injection, but I dont understand what exactly is happening. To the best of my knowledge, because I am not running this in some sort of container like TomCat, Spring isnt injecting anything, therefore my EntityManger would be null.
Ultimate question is how can I get around this? Do I have to run my unit tests in a container? That seems like bad practice.
Code for BatchDao:
public interface BatchDao {
public List<Batch> get_qry_Batch(ParameterBeanPost paramBean, QueryTableFields qrytblfields);
public QueryTableFields get_Query_TableFields(String qry_id);
}
Code for BatchDaoImpl:
public class BatchDaoJPA2Impl implements BatchDao {
@PersistenceContext(unitName="myPersistence")
private EntityManager entityManager;
//...lots of other variables
//...lots of other logic...
//Finally, we get to the method that thorws the NullPointerException
public QueryTableFields get_Query_TableFields(String qry_id)
{
try {
String qlString = "SELECT p FROM QueryTableFields p WHERE p.qry_id = ?1";
// The next line is what throws the NullPointerException
TypedQuery<QueryTableFields> query = entityManager.createQuery(qlString, QueryTableFields.class);
int param1 = Integer.parseInt(qry_id);
query.setParameter(1, (param1));
System.out.println("About to Execute the QueryTable");
return query.getSingleResult();
} catch (NoResultException e) {
// TODO Auto-generated catch block
System.out.println("No Result from QueryTable");
return null;
}
}
Code for the JUnit test:
import com.every.package.ever
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath*:/spring/applicationContext.xml")
public class BatchDaoJPA2ImplJUnitTest {
@Mock
private EntityManager entityManager;
BatchDaoJPA2Impl myBDI = new BatchDaoJPA2Impl();
@Test
public void testGet_Query_TableFields() {
QueryTableFields myQTFs = myBDI.get_Query_TableFields(null);
//Should just comeback with empty strings and not null.
assertNotNull(myQTFs);
}
}