views:

1381

answers:

3

I'm using jmockit with my tests and with one class I wish to test, uses InitialContext directly. So I have the following:

public class MyClass {
  public void myMethod() {
    InitialContext ic = new InitialContext();
    javax.mail.Session mailSession = ic.lookup("my.mail.session");

    // rest of method follows.....
  }

In my test case, I call this to use my "mocked" InitialContext class:

Mockit.redefineMethods(InitialContext.class, MockInitialContext.class);

What is the best way to mock the InitialContext class with jmockit.

I've already tried a few ways (such as using my own MockInitialContextFactory), but keeping stumbling into the same error:

NoClassDefFoundError: my.class.MockInitialContext

From what I can see on Google, mocking with JNDI is quite nasty. Please can anyone provide me with some guidance, or point me to a solution? That would be much appreciated. Thank you.

+1  A: 

In general, to mock JNDI, you will need to use a framework, such as EJBMock, that can provide a mock container in which to deploy your beans.

The other alternative is to refactor creating the context out of your code so that it is passed in (this is dependency injection refactoring), and then you should be able to substitute a mock at will.

cynicalman
A: 

You're getting the NoClassDefFoundError because my.class.MockInitialContext doesn't exist. You need to create that class if you're going to pass it as an argument to Mockit.redefineMethods(). Your MockInitialContext class would just need a method named lookup() that accepts a String parameter and returns a javax.mail.Session.

I like JMockit annotations, but you can look through the rest of that page for other examples of how to use JMockit.

Josh Brown
+1  A: 

I now its being a year since someone posted here, but since recently i was mocking EJB calls using JMockit i felt is the right thing to share. (Even though i haven't test it the code should be very similar)

You can define some Mocked object as field in your TestCase like:

@Mocked InitialContext mockedInitialContext;
@Mocked javax.mail.Session mockedSession;

then in your testXXX method you can define your Expectations(), after doing so is just matter of calling the method you want o test.

public void testSendindMail(){
     new Expectations(){
        {
    mockedInitialContext.lookup("my.mail.session");returns(mockedSession);    
     }
      };
    MyClass cl = new MyClass ();
    cl.MyMethod();//This need JNDI Lookup
}
jc