如何在EasyMock中替换间谍

时间:2017-04-21 17:42:16

标签: java mockito easymock

我在Mockito进行的测试很少,我尝试将其转换为EasyMock,但我不知道如何。在Mockito我可以使用spy,如何实现这样的目标。

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

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

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

}

1 个答案:

答案 0 :(得分:1)

简短的回答:你不能用EasyMock来做。

更长的答案:EasyMock不能为现有类“替换”方法,它只能生成继承者。因此,walkne将为TTTObject生成模拟并将所有调用从模拟重定向到原始TTTObject。

Check this link for more information