Jan Stanicek
Jan Stanicek

Reputation: 1281

How to test class with local connection to EJB

I am facing problem with testing class which has implemented some local connection to EJB in the constructor. This connection is used just inside the constructor and sets some private attributes of the instantiated class.

MyClass which I want to test:

public class MyClass {

  private String myValue;

  public MyClass() throws Exception {
    MyBeanLocal local = EJBFactory.getLocal(MyBeanLocal.class);
    myValue = local.fetchValue();
  }

  public void processValue() {
    ... do some String magic which should be tested ...
  }

  public String getValue() {
    return myValue;
  }

}

EJBFactory contains some enhanced lookup (with caching) and can return local or remote connection (remote requires server location).

MyBeanLocal interface

public interface MyLocalBean {
  public String fetchValue();
}

And finally my junit class where I want to test MyClass.processValue method:

public class MyClassTest {

  private MyClass myClass;

  @Before
  public void setUp() {
    myClass = new MyClass();
  }

  @Test
  public void testProcessValue() {
    Assert.assertEquals(myClass.processValue(), "MY EXPECTED VALUE");
  }

}

The question is how to test situation when I run JUnits in local machine (or some automatic test machine like Hudson or Jenkins) and bean runs on application server context which is different than my local one. I can't touch to production code, just need to write test.

Actually I don't need to make MyBeanLocal functional, but I need myValue set.

I was thinking about mocking, but I am not familiar with that.

Upvotes: 3

Views: 1102

Answers (2)

Rogério
Rogério

Reputation: 16380

You can use the JMockit mocking API (which I created) for such tests:

public class MyClassTest
{
    @Tested MyClass myClass;

    @Test
    public void processValue() {
        new NonStrictExpectations() {
            @Mocked EJBFactory fac;
            @Mocked MyBeanLocal mb;

            {
                EJBFactory.getLocal(MyBeanLocal.class); result = mb;
                mb.fetchValue(); result = "SOME VALUE";
            }
        };

        assertEquals(myClass.processValue(), "MY EXPECTED VALUE");
    }
}

The mocking of EJBFactory may even be omitted, if it still returns an object in the unit testing environment.

Upvotes: 1

Mike De Swert
Mike De Swert

Reputation: 101

When testing classes that involve database connections mocking is usually the best way to go. There are several frameworks that make mocking objects a lot easier, one of which is Mockito.

You can find more info about it here

Martin Fowler also wrote a good article about when to use mocks and what the difference is between a mock and a stub. Here's a link to the article.

Upvotes: 0

Related Questions