Mocking of RestTemplate is giving always null - mockito

I am trying to mock the RestTemplate method through mockito but it always returning null.
mockito code:
Mockito.when(template.exchange(ArgumentMatchers.any(), ArgumentMatchers.any(),
ArgumentMatchers.<HttpEntity<?>>any(), Mockito.<Class<CountDto>>any()))
.thenReturn((ResponseEntity<CountDto>) responseEntity);
actual code:
ResponseEntity<CountDto> responseEntity = template.exchange(envargs.get("CountURL"),
HttpMethod.GET,getHttpEntity(accessToken), CountDto.class);
Please let me know the issue in the code.

You can try below code
ResponseEntity<CountDto>) responseEntity = new ResponseEntity<>(new CountDto(), HttpStatus.OK);
Mockito.when(template.exchange(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
.thenReturn(responseEntity);

Related

What causes "assignedElements is not a function" in this Stencil.js Jest test?

I am getting an error in Jest test cases that says assignedElements is not a function.
In the code, I am trying to query slots and then fetch the value as mentioned below:
let slot = this.element.shadowRoot?.querySelector('slot');
const testItems = slot.assignedElements({flatten:true});
This code is working fine on most of the browsers, but it is failing in Jest test cases. I thought of mocking and spying on this API, but no luck there either.
Some environments may not have slot.assignedElements yet, but it is super easy to polyfill on top of slot.assignedNodes:
if (!HTMLSlotElement.prototype.assignedElements) {
HTMLSlotElement.prototype.assignedElements = function (...args) {
return HTMLSlotElement.prototype.assignedNodes
.apply(this, args)
.filter((n) => n instanceof Element)
}
}
Change .assignedElements() to .assignedElements?.()
and .assignedNodes() to .assignedNodes?.()

Can I fetch a local variable's value from a mocked function?

I have a function say MyFunction(arg) which I have mocked.
Inside the function, another function is called and the result of the second function is assigned to a local variable(say myVar) declared inside MyFunction(arg).
Can I use mockito anyway to fetch the value of myVar in my test function?
Adding code :
OrderOperations.java
public OrderResponse createOrder(Orders order){
OrderResponse orderResponse = new OrderResponse();
ManipulatedOrder = partnerOrder;
partnerOrder = parseXML(order) //This function manipulates the details of order object and gives back the result.
String xmlRequest = xs.toXML(partnerOrder); //The response is converted to XML
//Few modifications are done to the xmlRequest and then it is sent to another function
orderResponse = invokeAPI(xmlRequest); //This function uses the xmlRequest.
return orderResponse;
}
I want to test this function using JUNIT, mock this function and in someway want to capture what is being sent to invokeAPI if I pass test values to the Orders object.

Jest mock with "new" instance

I'm trying to test a method inside a class (ts). Inside that method, I'm creating a new instance of an external module.
public cancelEdit() {
this.candidate = new Candidate(this.originalCandidate);
this.controller.reset();
this.editMode = false;
}
When I check the code coverage from the test I notice that Candidate method is also covered (which means that I don't have a mock to this class).
What is wrong here? It's me using the "new" instance or I'm doing the mock in the wrong way?

Handling "204 no content" in Spring-Integration

My int-http:outbound-gateway is returning "204 no content" . As a result my UI layer is failing because it is expecting a not null payload. Is there any way to handle this situation in Spring-Integration?
The HttpRequestExecutingMessageHandler does this:
if (this.expectReply) {
...
AbstractIntegrationMessageBuilder<?> replyBuilder = null;
if (httpResponse.hasBody()) {
Object responseBody = httpResponse.getBody();
replyBuilder = (responseBody instanceof Message<?>) ?
this.getMessageBuilderFactory().fromMessage((Message<?>) responseBody) : this.getMessageBuilderFactory().withPayload(responseBody);
}
else {
replyBuilder = this.getMessageBuilderFactory().withPayload(httpResponse);
}
replyBuilder.setHeader(org.springframework.integration.http.HttpHeaders.STATUS_CODE, httpResponse.getStatusCode());
return replyBuilder.copyHeaders(headers).build();
}
return null;
So, if you don't use <int-http:outbound-channel-adapter> you definitely get some reply and there will be that HttpHeaders.STATUS_CODE header with the HttpStatus.NO_CONTENT as value.
As you see the payload of the message depends of the httpResponse.hasBody() and I guess in case of HttpStatus.NO_CONTENT there is really no body. So, payload is a full ResponseEntity.
Now, please, share more info how does it work for you? How do you get a null payload?

nunit tests do not complete when testing async mvc5 controller (vs 2015)

I have an mvc 5 controller that makes use of some async data access code. I've written a simple test using nUnit. The test doesn't complete, it just spins until i cancel it. afaik i've set up the test correctly; it's awaiting the controller action is marked as async and returns a task. Am i missing something? Interestingly, the test works when i mock out the dependencies using moq, but if i go for an integration test with the actual dependencies in place, it just spins forever.
the a simplified test:
[Test]
public async Task Get_WhenProductHasData_ReturnsView()
{
// Arrange
...
// Act
PartialViewResult actualResult = await _controller.Widget(_productId1) as PartialViewResult;
// Assert
Assert.That(actualResult, Is.Not.Null);
...
}
And here's the simplified controller
public async Task<ActionResult> Widget(string productId)
{
ProductStats stats = await _statsService.GetProductStatsAsync(productId);
return PartialView(stats);
}
Try this instead:
[Test]
public async Task Get_WhenProductHasData_ReturnsView()
{
// Arrange
...
// Act
var result = await _controller.Widget(_productId1);
// Assert
Assert.That(result as PartialViewResult, Is.Not.Null);
}
Note that the "Act" line is simply awaiting and the result is then cast as a PartialViewResult on the Assert.That line, if it was null or not a PartialViewResult type it would return null. Either way you get what you're looking for.

Resources