-3

I have the method similar to following structure.

method1(Object obj,byte[] myarray)
{
    mymanager.dbcall1();
    mymanager2.dbcall2();
}

Now I want to write the JUNIT test case which can actually mock these managers who are doing the dbcalls ?Finally I want to compare the results. These managers are available only at run time of the application.

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
user1844840
  • 1,937
  • 3
  • 16
  • 13

3 Answers3

1

Do you want to test method1()? If so, I assume that you have a setter for mymanager in the enclosing class, which will enable you to (using Mockito):

@Before
public void setUp()
{
    MyClass my = new MyClass();
    MyManager mgr = mock( MyManager.class );
    my.setManager( mgr );

    // Similar for mymanager2
}

Then all method calls on mgr will just return null. If you need other return values, the doReturn(...).when( mgr ).dbcall1() construct can be used.

Cheers,

Anders R. Bystrup
  • 15,729
  • 10
  • 59
  • 55
0

Here you go, I searched on stack overflow and found pretty much something that someone has asked before:

Testing an EJB with JUnit

It's based on EJB but we don't know what you are using right now, but this might have some common principles.

Community
  • 1
  • 1
Davos555
  • 1,974
  • 15
  • 23
0

First, you'll need some dependency injection. There are many ways to accomplish this, but here's a simple one:

private I_DatabaseManager mymanager = null;

method1(Object obj,byte[] myarray)
{
    getDatabaseManager().dbcall1();
    getDatabaseManager().dbcall2();
}

private I_DatabaseManager getDatabaseManager() {
    if (mymanager == null) {
          return getProductionImplementationOfDatabaseManager();
    }
    return mymanager;
}

protected void setDatabaseManagerImplementation(I_DatabaseManager newImplementation) {
    mymanager = newImplementation;
}

Then, in your test code you can create a mock class which implements the I_DatabaseManager interface and set this mock implementaion in your test.

Chris Knight
  • 24,333
  • 24
  • 88
  • 134