how to mock resttemplate with ArgumentMatcher? - java

I want to mock the restTemplate.exchange when I tried the following code to do that.
Mockito.when(restTemplate.exchange(ArgumentMatchers.eq(clientEndpoint.getUrl()),ArgumentMatchers.eq(HttpMethod.POST),
ArgumentMatchers.eq(new HttpEntity<>(ArgumentMatchers.any(String.class),ArgumentMatchers.eq(headers))), ArgumentMatchers.eq(Map.class))).thenReturn(rEntity);
I got the following error,
How can I resolve this issue?
Thanks in advance!

I solved the issue, it seems there is no ArgumentMatchers.eq then followed by a new instance, I changed the code like this
Mockito.when(restTemplate.exchange(ArgumentMatchers.eq(clientEndpoint.getUrl()),ArgumentMatchers.eq(HttpMethod.POST),
new HttpEntity<>(ArgumentMatchers.any(String.class),ArgumentMatchers.eq(headers)), ArgumentMatchers.eq(Map.class))).thenReturn(rEntity);
and it works to me now

Related

Expression Expected Error encountered in JUnit5 Test

I am new in unit testing and I am stuck with this error. I wonder if anyone here got an insight as to how I can resolve this issue.
So this is a snippet of my unit test.
#Test
void shouldFindByStatus() {
when(repository.findByBookingStatus(anyString(),Sort.by("id").descending())).thenReturn(getBookingEntityForFilterByStatus());
when(mapper.toDomain(any(List<BookingEntity.class))).thenReturn(getBookingFilterResponseDTO());
List<BookingFilterResponseDTO> underTest = adapter.findByBookingStatus("CANCELLED");
assertNotNull(underTest);
}
The error I encountered is this part:
(any(List<BookingEntity.class)))
It says that "List" is an expected expression. Now the problem is if I remove the List, it will throw a different error since I declared it as List on my mapper class.
This is my mapper class.
List<BookingFilterResponseDTO> toDomain(List<BookingEntity> bookingEntity);
If anyone here got an idea as to how I can resolve the said issue. I would highly and sincerely appreciate it. Thanks!

How to enter inside a bracket [] when testing API response body using MockMvc .jsonpath() method

I am new to MockMvc and jsonpath. I did some API testing with rest assured and hamcrest matchers before but I can't figure something out.
How can I get inside the bracket for this response body?
As you can see the response body contains List of users hence the brackets.. So I don't know what to write inside my expression so I have just written "" but it seems that triggers compiler error.
Any help is appreciated
Best,
I should've used expression as "$.[0]"
This solved my problem.

Consuming Hateoas: Non-matching JSON-request generated

Hello dear Stack Overflow!!! :)
I have a bit of a problem. I am attempting to consume a Hateoas-based application in a project and I'm having issues with Hateoas and it generating a faulty JSON-request for a test. I will provide some code examples!
Basically, I use a JSONconverter that tries to convert my request body(post) to JSON but it throws an error with what I actually get. Some information and code:
Here is my ObjectMapper that I am using:
ObjectMapper objectMapper = (ObjectMapper) bean;
objectMapper.registerModules(new Jackson2HalModule());
Here is my converter config where I plug the objectmapper and the supported media types:
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(Arrays.asList(MediaTypes.HAL_JSON, MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_JSON_UTF8));
converter.setObjectMapper(objectMapper);
Here is my RestTemplate where I plug the Jackson 2 Http Converter I just made:
#Bean
public RestTemplate uttagRestTemplate(RestTemplateBuilder builder) {
return builder.messageConverters(mappingJackson2HttpMessageConverter, new StringHttpMessageConverter(Charset.forName("UTF-8")))
Here is the test I run with the output:
mockServer.expect(requestTo(url + "/person/" + id + "/links")).andExpect(header("Content-type", MediaType.APPLICATION_JSON_UTF8.toString()))
.andExpect(header("accept", MediaType.APPLICATION_JSON_UTF8.toString()))
.andExpect(content().string(jsonConverter.toJson(Arrays.asList(link)))).andExpect(method(HttpMethod.POST)).andRespond(withSuccess());
Finally, here is my test output(don't mind the data, it's just test data):
Expected :[{"id":2112,"rel":"EZyb","href":"dspK0XickvvcMw0","type":"RaAmwWkZHlagrcQ","length":992539719,"title":"OuaRoPRClRpvprg"}]
Actual :"[{\"id\":2112,\"rel\":\"EZyb\",\"href\":\"dspK0XickvvcMw0\",\"type\":\"RaAmwWkZHlagrcQ\",\"length\":992539719,\"title\":\"OuaRoPRClRpvprg\"}]"
It seems to do something really weird with the "actual" json-generated body. I'd like to have it match my expected, but no luck.
I've tried solving this, and if I remove the MediaType.HAL_JSON from my MappingJacksonConverter somehow it works in my tests, but then I can't consume the hateoas client. I need the media type there for it to work.
I've also tried writing my expected JSON with my MappingJackson writer, but it produces the exact same expected output.
Does anybody know what's going on here and can help me with this? Do you know how I may generate correct JSON-body to get the assert to work? Frankly it's doing my head in - and choosing between functioning tests without the media type and being able to consume the hateoas application with it obviously isn't an option for me. :(
Cheers for reading if you made it this far! :) Any pointers are welcome.
I figured out what it was. With the new config, it seems that the application automatically converts to json and I didn't need to use my own jsonConverter anymore. So what was going on as basically a toJson conversion on an already jsonified object.
After removing my own jsonconverter implementation, it now functions correctly.

#PreAuthorize("isAuthenticated()") returns nullpointer exception instead accessdeniedexpection [method level security]

I'm currently stuck on these problem. when I tried using #PreAuthorize("hasRole('ROLE_USER')") it works, but not on #PreAuthorize("isAuthenticated()"). I'm trying to make it return a accessdeniedexception but it returns nullpointerexception.
does anyone have encountered these kind of issue before?
I never thought that there is a custom class that extends the SecurityRoot.class but forgot that TrustResolver.class is not pass causing the nullpointer exception. I have just set the trustResolver and it work as I wanted.

XMLBeans get_store() method returns null

I am developing a Axis2 based WebServices with XMLBeans binding. I have generated the code by using WSDL2Java generator and tried testing it with sample values set in the request.
In one of the setter methods (auto-generated code) I found the below code. The method get_store() returns a null value and hence I get a NullPointerException.
target = (org.apache.xmlbeans.SimpleValue)
get_store().find_element_user(TRANSACTIONTYPE$0, 0);
I tried Google to find the solution and found similar issue with no solution specified.
Is there any work around for this issue?? Kindly help me
This issue got resolved!!
I was actually trying to instantiate a response object in a normal Java way and hence i got the above mentioned exception while running my WebServices.
Wrong way - ResponseType responseType = new ResponseType();
Correct way - ResponseType responseType = ResponseType.Factory.newInstance();

Categories

Resources