让Mockito和Powermock正确地抛出错误

时间:2011-09-27 13:57:08

标签: java testing mockito powermock

我有以下代码

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

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

失败,预期:< [测试例外]>但是:< [缺少方法调用验证(模拟)这里: - >在org.powermock.api.mockito.internal.invocationcontrol.MockitoNewInvocationControl.expectSubstitutionLogic(MockitoNewInvocationControl.java:65)正确验证的示例:verify(mock).doSomething()此外,此错误可能会显示,因为您验证以下任一项:final / private / equals()/ hashCode()方法。这些方法无法进行存根/验证。 ]>

有关如何解决此问题的任何想法?尝试了我能想到的一切。

由于

1 个答案:

答案 0 :(得分:3)

错误实际上来自testRetrieveMongoDBSuccessful();看起来你的verify()不是很正确,但是Mockito在下一次时间之前不能告诉你。

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

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