在play框架测试中无法从匿名回调内部传递异常

时间:2014-01-08 18:17:02

标签: java playframework-2.0 integration-testing

我将以下集成测试作为Play Framework项目的一部分。

@Test(expected = OAuthProblemException.class)
public void testFailedCredentials() throws OAuthProblemException, OAuthSystemException {
    running(testServer(3333, fakeApplication(inMemoryDatabase())), HTMLUNIT, new F.Callback<TestBrowser>() {
        public void invoke(TestBrowser browser) throws OAuthProblemException, OAuthSystemException {
            OAuthClientRequest request = OAuthClientRequest
                    .tokenLocation("http://localhost:3333/oauth2/access_token")
                    .setGrantType(GrantType.PASSWORD)
                    .setClientId("client_id")
                    .setClientSecret("client_secret")
                    .setUsername("username")
                    .setPassword("password_should_not_pass")
                    .buildBodyMessage();

            OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

            oAuthClient.accessToken(request); //throws OAuthProblemException
        }
    });
}

oAuthClient.accessToken(request);会抛出OAuthProblemException,这是正确的。我的问题是,由于匿名内部回调,我没有可能传播异常,并像我的代码中那样执行@Test(expected = OAuthProblemException.class)之类的操作。

我可以捕获异常并将测试标记为catch部分内的成功,但Play Framework测试没有内置于success()或fail()方法(我能找到),导致我做了一些愚蠢的事情像这样

try {
    oAuthClient.accessToken(request);
    assertThat("This credentials should fail").isEmpty();//Force a fail
} catch (OAuthProblemException e) {
    assertThat(e).isInstanceOf(OAuthProblemException.class);//Force a success. I could probably skip this line
}

我认为这看起来不太直观。有什么建议如何以更好的方式解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:1)

好的,找到了fail()函数: - )

import static org.junit.Assert.*;

有了这个,我可以做到以下几点:

try {
    oAuthClient.accessToken(request);
    fail();
} catch (OAuthProblemException e) {
    //success
}

我认为这看起来好多了。如果您能想到其他解决方案,例如传播异常或类似的方法,我很乐意听到它。

(愚蠢的我)

相关问题