-3

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);
    }

}
R4F6
  • 782
  • 1
  • 9
  • 26
  • 2
    As much as I sympathize with your situation, it is off-topic here. All you can do is try to find a **recent** tutorial from a serious source that is simple enough for you to get started. Other notions that you need to understand are what are application servers, web services, backend and frontends... – njzk2 Sep 17 '15 at 20:07
  • People have written entire books about this. Unless you ask a more specific question, we simply cannot help you. – Kevin Sep 17 '15 at 20:09
  • I got thrown into the world of Java EE upon starting at my first job as well, so I understand. Read through the tutorials on Oracle's website (you can also download them as a PDF), there is a lot of information that may be useful to you. Once you do that, try studying some of the code, and if you see something that you don't understand, just look up what it is. Eventually, more and more will become familiar to you. I'm able to work with it pretty well now, but there is still a lot to learn. – Evan LaHurd Sep 17 '15 at 20:13
  • I was writing an answer for you--tried to get it in fast because I knew they'd close this question but didn't make it in time. I posted it as a github wiki article on my mostly unused repo if you're interested: https://github.com/BillKress/groovy-scripting/wiki/Temporary-comment-for-SO-user--ignore (This just describes spring a little, telling you what J2EE is it harder--I guess the shortest version is that it's a bunch of useful libraries and a server bundled together--but that's a huge understatement, sorry--limited space and all) – Bill K Sep 17 '15 at 20:26
  • 1
    1) Java EE and Spring are full competitors. 2) Start here: http://stackoverflow.com/q/18369356 – BalusC Sep 17 '15 at 21:11
  • @R4F6 Are you calling `@InitMocks`? Possible duplicate of [@Mock, NullPointerException](http://stackoverflow.com/q/25305231/1768232) – durron597 Sep 18 '15 at 20:51
  • @durron597, No, should I be? What does `@InitMocks` do? – R4F6 Sep 21 '15 at 16:25

1 Answers1

0

@Mock is just an annotation, it has no behavior on it's own. The behavior that actually populates these fields with a mock can come from one of two things

  1. Using MockitoAnnotations.initMocks() will parse the class and create a mock for every field annotated with @Mock
  2. Using MockitoJUnitRunner in your @RunWith statement instead of SpringJUnit4ClassRunner.
    • You probably don't want to do this if you're using the Spring runner for other behavior

So, just add MockitoAnnotations.initMocks(this) in your @Before method and you'll start mocking EntityManager instead of having it be null.

If you want to inject an actual EntityManager, it might be somewhat more difficult. However, that is outside the scope of your question, as you are asking about how to mock it. On this issue, see this: How to test Spring Data repositories? and this: Spring fails to inject entity manager factory

Community
  • 1
  • 1
durron597
  • 31,968
  • 17
  • 99
  • 158
  • Follow on question: What is the difference between an `EntityManager` and and `EntityMangerFactory`? – R4F6 Sep 21 '15 at 17:39
  • @R4F6 See this: [Injecting EntityManager Vs. EntityManagerFactory](http://stackoverflow.com/q/1310087/1768232) – durron597 Sep 21 '15 at 17:44