在 RestEasy 3.x 中,我使用 ClientRequestFilters。在下面的示例中,有一个持续集成 (CI) 服务器侦听在后台运行的请求。测试和 CI 服务器使用相同的数据库和实体类。
假设名为“test-tenant”的租户确实存在,并且存在属于该租户的用户“root”,并且该用户具有下面指定的密码。
private static final String BASE_URI = "http://localhost:" + PORT;
@Test(groups = "functionalTests")
public void testGetTenant() throws Exception {
Client client = ClientBuilder.newClient();
ResteasyWebTarget target = (ResteasyWebTarget)client.target(BASE_URI);
client.register(new AddAuthHeadersRequestFilter("root", "DefaultPasswordsAre:-("));
TenantResource resource = target.proxy(TenantResource.class);
RestTenant restTenant = resource.getTenant(tenant.id().value().toString());
assertThat(restTenant.getName(), is("test-tenant"));
assertThat(restTenant.isActive(), is(true));
}
AddAuthHeadersRequestFilter 类:
public static class AddAuthHeadersRequestFilter implements ClientRequestFilter {
private final String username;
private final String password;
public AddAuthHeadersRequestFilter(String username, String password) {
this.username = username;
this.password = password;
}
@Override
public void filter(ClientRequestContext requestContext) throws IOException {
String token = username + ":" + password;
String base64Token = Base64.encodeBase64String(token.getBytes(StandardCharsets.UTF_8));
requestContext.getHeaders().add("Authorization", "Basic " + base64Token);
}
}
import 语句(假设您只是将测试和静态类粘贴到单个 TestNg 测试类文件中):
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.testng.annotations.Test;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.ws.rs.client.ClientRequestContext;
import javax.ws.rs.client.ClientRequestFilter;
import org.apache.commons.codec.binary.Base64;