PowerMock + EasyMock意外的方法调用

时间:2013-10-17 21:53:25

标签: unit-testing junit4 easymock powermock

我有一个这样的方法,我想进行单元测试

public void update(String collectionName, BasicDBObject query, BasicDBObject updateObj){
    try{
        DBCollection collection = getCollection(collectionName);
        collection.update(query, updateObj, true, false);

    } catch (MongoException e) {
        if (e.getMessage().startsWith("can't call something")) {
               refreshConnection(collectionName);
            } else {
                throw e;
            }
    }
}

测试代码如下。我在单元测试用例的注释中尝试了两种方法,目前已对其进行了评论。

@Test
public void testUpdate(){
    MongoStore store = PowerMock.createStrictPartialMockForAllMethodsExcept(MongoStore.class, "update");
    DBCollection collection = PowerMock.createMock(DBCollection.class);

    BasicDBObject updateobj = new BasicDBObject("test","shrikar");
    String name = "testcoll";
    String id = "123";
    BasicDBObject query = new BasicDBObject("id",id);
    EasyMock.expect(store.getCollection(name)).andReturn(collection);
    //EasyMock.expect(collection.update(EasyMock.anyObject(BasicDBObject.class),EasyMock.anyObject(BasicDBObject.class),EasyMock.anyBoolean(),EasyMock.anyBoolean()));
    //EasyMock.expect(collection.update(query,updateobj,true,false));
    PowerMock.replayAll();
    store.update(name,query,updateobj);
    EasyMock.expectLastCall().times(1);

    PowerMock.verifyAll();
}

在所有情况下,我一直在

Unexpected Method call DBCollection.update({"id":"123"},{"test":"shrikar"}, true, false)

我错过了什么?

1 个答案:

答案 0 :(得分:0)

好的,我发现了我忘记将Mongo * .class添加到PrepareForTest的问题

@PrepareForTest({MongoStore.class,MongoOptions.class,Mongo.class, BasicDBObject.class,DBCursor.class,DBObject.class})