我有类似的方法:
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class ProductFacadeImplTest {
@Mock
private NutritionixHeader nutritionixHeader;
@Mock
private RestTemplate restTemplate;
@InjectMocks
private ProductFacadeImpl productFacadeImpl;
@Mock
private UriComponentsBuilder uriComponentsBuilder;
@Mock
private ResponseEntity responseEntity;
@Mock
private HttpHeaders httpHeaders;
@BeforeEach
void setUp() {
productFacadeImpl = new ProductFacadeImpl(nutritionixHeader, restTemplate);
}
@Test
void addUniversalHeaderForRequest() {
//given
given(nutritionixHeader.getNutritionixAppId()).willReturn("id");
given(nutritionixHeader.getNutritionixAppKey()).willReturn("key");
//when
productFacadeImpl.addUniversalHeaderForRequest();
ArgumentCaptor<HttpEntity> httpEntityCapture = ArgumentCaptor.forClass(HttpEntity.class);
ArgumentCaptor<HttpHeaders> httpHeadersCaptor = ArgumentCaptor.forClass(HttpHeaders.class);
verify(httpHeaders).set(eq("x-app-id"), eq("id"));
verify(httpHeaders).set(eq("x-app-key"), eq("key"));
HttpHeaders headers = httpEntityCapture.getValue().getHeaders();
assertEquals("id",
headers.entrySet()
.stream()
.filter(entry -> entry.getKey().equals("x-app-id"))
.map(Entry::getValue)
.flatMap(Collection::stream)
.findFirst()
.orElse(""));
}
}
我想测试我的方法是否向HTTP请求中正确添加了标头。
我的测试如下:
Wanted but not invoked:
httpHeaders.set("x-app-id", "id");
-> at com.application.nutritionix.service.ProductFacadeImplTest.addUniversalHeaderForRequest(ProductFacadeImplTest.java:196)
Actually, there were zero interactions with this mock.
但是当我启动它时,我收到的信息是:
ArgumentCaptor
我知道我想使用httpEntityCapture
,但是我无法确定如何正确使用{{1}}来解决此示例。
感谢您对实现目标的建议。