1

I have few test in Mockito and I try to convert it to EasyMock, but I don't know how. In Mockito I can use spy, how to achive something like this.

public class TTTCollection {

private MongoCollection mongoCollection;
protected MongoCollection getMongoCollection() {
    return mongoCollection;
}
private static final String dbName = "TTT";
private static final String collectionName = "ruchy";


public TTTCollection(){
    DB db = new MongoClient().getDB(dbName);
    mongoCollection = new Jongo(db).getCollection(collectionName);
}

public boolean deletedb() {
    try {
        getMongoCollection().drop();
        return true;
    } catch (Exception e) {
        return false;
    }
} 

public boolean save(TTTObject object) {
    try {
        getMongoCollection().save(object);
        return true;
    } catch (Exception e) {
    return false;
    }

and tests in Mockito :

public class TTTCollectionTest {

TTTCollection collection;
TTTObject object;
MongoCollection mongoCollection;    

@Before
public void Setup(){
    collection = spy(new TTTCollection());
    mongoCollection = mock(MongoCollection.class);
    object = new TTTObject(1,2, 2, "x");
}


@Test
public void testDeleteCollection(){
    doReturn(mongoCollection).when(collection).getMongoCollection();
    assertTrue(collection.deletedb());
}

@Test
public void testSave() {
    doReturn(mongoCollection).when(collection).getMongoCollection();
    assertTrue(collection.save(object));
} 

and

public class TTTCollectionEMTest extends EasyMockSupport {

TTTCollection collection;
TTTObject object;
MongoCollection mongoCollection;


@Before
public void Setup(){
    mongoCollection = EasyMock.createMock(MongoCollection.class);
    collection = new TTTCollection(); // how to spy it ?
   object = new TTTObject(1,2, 2, "x");
}

@Test
public void testDeleteCollection(){

    EasyMock.expect(collection.getMongoCollection()).andReturn(mongoCollection);
    replayAll();
    assertTrue(collection.deletedb());

}
Blasanka
  • 21,001
  • 12
  • 102
  • 104

1 Answers1

1

Short answer: you cannot do it with EasyMock.

Longer answer: EasyMock cannot "substitute" methods for existing class, it can just generate inheritor. So walk-around will be generating mock for TTTObject and redirect all calls from the mock to original one TTTObject.

Check this link for more information

MaximSadym
  • 61
  • 4