【发布时间】:2017-04-21 17:42:15
【问题描述】:
我在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());
}
【问题讨论】:
-
this question 及其答案对您有帮助吗?
-
不多,我无法根据需要调整代码