【发布时间】:2021-12-03 22:31:57
【问题描述】:
我正在尝试使用 LinkedMultiValueMap 模拟方法,但没有任何成功。长话短说,几天前我刚刚开始使用 Mockito 和 Junit 进行测试,实际上我不知道自己在做什么。我将提供我的测试方法代码,以及我编写模拟测试的尝试。
@Service
public class VaultService {
public VaultService() {
String baseUrl = System.getenv("VAULT_HOST") + "/api/v" + System.getenv("VAULT_API_VERSION");
String userAgent = System.getenv("APPLICATION_NAME") + "/" + System.getenv("APPLICATION_VERSION");
webClient = WebClient.builder()
.baseUrl(baseUrl)
.defaultHeader(HttpHeaders.USER_AGENT, userAgent)
.defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
}
@Scheduled(fixedDelay = 1200000)
public void authenticate() {
LinkedMultiValueMap<String, String> login = new LinkedMultiValueMap<>();
login.add("username", System.getenv("VAULT_USERNAME"));
login.add("password", System.getenv("VAULT_PASSWORD"));
webClient.post()
.uri("/auth")
.body(BodyInserters.fromMultipartData(login))
.retrieve()
.bodyToMono(AuthenticationResponse.class)
.map(authenticationResponse -> {
setSessionId(authenticationResponse.sessionId);
return authenticationResponse;
})
.block();
}
}
这是我编写模拟测试失败的尝试:
class VaultServiceTest {
private WebClient webClientMock;
@BeforeEach
void setup() {
webClientMock = mock(WebClient.class);
}
@Test
void authenticate() {
VaultService vaultService = new VaultService();
LinkedMultiValueMap<String, String> testAuthenticate = mock(LinkedMultiValueMap.class);
when(testAuthenticate.get("password")).thenReturn(Collections.emptyList());
}
}
【问题讨论】:
-
永远不要模拟
LinkedMultiValueMap这样的集合类型。做一个真正的。 -
或任何类型的纯数据,无需修改任何行为。 @LouisWasserman
-
@LouisWasserman >> 你的意思是,用 LinkedMultiValueMap 制作地图?
-
我的意思是做一个真正的
LinkedMultiValueMap。不要模拟它,构建它。