gpt4 book ai didi

java - 如何在EasyMock中替换spy

转载 作者:行者123 更新时间:2023-11-30 06:46:52 25 4
gpt4 key购买 nike

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

}

最佳答案

简短的回答:你不能用 EasyMock 做到这一点。

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

Check this link for more information

关于java - 如何在EasyMock中替换spy,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43548962/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com