2

我有以下代码

@PrepareForTest({Mongo.class, XYMongo.class, DB.class})
public class XYMongoTest extends UnitTest{

String host = Play.configuration.getProperty("mongo.host");
int port = Integer.parseInt(Play.configuration.getProperty("mongo.port"));  
String name = Play.configuration.getProperty("mongo.name");

@Test
public void testRetrieveMongoDBSuccessful() throws UnknownHostException, MongoException, Exception
{
    Mongo mongoMock = mock(Mongo.class);
    DB mockDB = mock(DB.class);

    PowerMockito.whenNew(Mongo.class).withArguments(host, port).thenReturn(mongoMock);

    when(mongoMock.getDB(name)).thenReturn(mockDB);

    XYMongo.getMongoDB();

    verify(mongoMock.getDB(name));
}


@Test
public void testRetrieveMongoDBFailUnkownHost() throws Exception
{   
    try
    {

        PowerMockito.mockStatic(Mongo.class);

        PowerMockito.whenNew(Mongo.class).withArguments(host, port).thenThrow(new UnknownHostException("Test Exception"));

        XYMongo.getMongoDB();

        PowerMockito.verifyNew(Mongo.class).withArguments(host, port);
    }
    catch (Exception e) 
    {
        assertEquals("Test Exception", e.getMessage());
    }
}}

第一个测试通过正常,第二个测试失败,测试错误为

失败,预期:<[Test Exception]> 但是:<[ Missing method call for verify(mock) here:-> at org.powermock.api.mockito.internal.invocationcontrol.MockitoNewInvocationControl.expectSubstitutionLogic(MockitoNewInvocationControl.java:65)正确验证示例: verify(mock).doSomething() 此外,此错误可能会出现,因为您验证了以下任一方法:final/private/equals()/hashCode() 方法。这些方法不能被存根/验证。]>

有想法该怎么解决这个吗?尝试了我能想到的一切。

谢谢

保罗

4

1 回答 1

3

错误实际上来自testRetrieveMongoDBSuccessful(); 看起来你的verify()做法不太正确,但 Mockito直到你下次与它互动时才能告诉你。

尝试将最后一行替换为testRetrieveMongoDBSuccessful()

verify(mongoMock).getDB("name");

于 2011-09-28T02:47:14.917 回答