我正在尝试测试我的第一个 Pact 文件,但我一直在为向生产者发出的请求设置标头。
当向具有无效用户 ID 的用户 API 发出请求时,我正在尝试获取 404,如以下 Pact 文件中所定义:
{
"consumer": {
"name": "ios-client"
},
"provider": {
"name": "user-service"
},
"interactions": [
{
"description" : "Request for a User Id that does not exist should return 404",
"provider_state": "User with id NOPE does not exist",
"request": {
"method": "GET",
"path" : "/users/NOPE"
},
"response": {
"status": 404,
"body" : ""
}
}
]
}
失败的测试如下:
import au.com.dius.pact.consumer.DefaultRequestValues;
import au.com.dius.pact.consumer.dsl.PactDslRequestWithPath;
import au.com.dius.pact.consumer.dsl.PactDslRequestWithoutPath;
import au.com.dius.pact.provider.junit.PactRunner;
import au.com.dius.pact.provider.junit.Provider;
import au.com.dius.pact.provider.junit.State;
import au.com.dius.pact.provider.junit.loader.PactBroker;
import au.com.dius.pact.provider.junit.target.HttpTarget;
import au.com.dius.pact.provider.junit.target.Target;
import au.com.dius.pact.provider.junit.target.TestTarget;
import org.junit.Before;
import org.junit.runner.RunWith;
import org.springframework.boot.SpringApplication;
import org.springframework.http.HttpHeaders;
import .....UserServiceApplication;
import .....UserControllerIT;
import java.util.HashMap;
import java.util.Map;
@RunWith(PactRunner.class)
@Provider("user-service")
@PactBroker(host="${pactbroker.hostname:localhost}", port = "80")
public class PactTest {
@TestTarget
public final Target target = new HttpTarget(8080);
@DefaultRequestValues
public void defaultRequestValues(PactDslRequestWithoutPath request) {
Map<String, String> headers = new HashMap<>();
headers.put(HttpHeaders.AUTHORIZATION, UserControllerIT.AUTH_TOKEN1);
request.headers(headers);
System.out.println("THIS IS NEVER CALLED");
}
@State("User with id NOPE does not exist")
public void userWithIdNopeDoesNotExist_andServerRunning() {
String[] args = new String[1];
args[0] = ""; //don't ask
SpringApplication.run(UserServiceApplication.class, args);
}
}
永远不会调用 defaultRequestValues 方法,永远不会设置授权标头,并且服务返回 401(在这种情况下这是正确的行为,但这不是我要测试的)。
有什么想法可以在此测试中设置授权标头吗?谢谢。