开发者

Getting Mockito and Powermock to throw error correctly

开发者 https://www.devze.com 2023-04-07 18:24 出处:网络
I have the following code @Pre开发者_运维技巧pareForTest({Mongo.class, XYMongo.class, DB.class})

I have the following code

@Pre开发者_运维技巧pareForTest({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());
    }
}}

The first test passes fine and the second fails with the test error being

Failure, expected:<[Test Exception]> but was:<[ Missing method call for verify(mock) here: -> at org.powermock.api.mockito.internal.invocationcontrol.MockitoNewInvocationControl.expectSubstitutionLogic(MockitoNewInvocationControl.java:65) Example of correct verification: verify(mock).doSomething() Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods. Those methods cannot be stubbed/verified. ]>

Any ideas on how to fix this? Tried everything I can think of.

Thanks

Paul


The error is actually coming from testRetrieveMongoDBSuccessful(); it looks like you've got the verify() not-quite-right, but Mockito can't tell you that until the next time you interact with it.

Try replacing the last line of testRetrieveMongoDBSuccessful() with:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号