不能在play框架测试中从匿名回调内部传递异常
-
20-12-2019 - |
题
我有以下集成测试作为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
}
我不认为这看起来很直观。任何建议如何以更好的方式解决这个问题?
谢谢!
解决方案
好的,找到fail()函数:-)
import static org.junit.Assert.*;
有了这个,我可以做到以下几点:
try {
oAuthClient.accessToken(request);
fail();
} catch (OAuthProblemException e) {
//success
}
我想看起来好多了。如果您能想到替代解决方案,例如向上传播异常或类似的方法,我很乐意听到它。
(愚蠢的我)
不隶属于 StackOverflow