Why doesn't Spring WebFlux MockServerRequest allow an empty body? - spring

I'm writing some tests for a Spring WebFlux application and I'm trying to mock a scenario where a request doesn't have a body. I reached for the built-in MockServerRequest, figuring I'd use the built-in mock over making my own. It does allow constructing an instance without a body, but my tests are failing as all of its methods for extracting the body contain an assertion that the body is not null. This doesn't seem to line up with how an actual request would behave. It's totally possible to make a request with no body. I'd also say it's reasonable to have code that checks to see if there's a body, as backed up by the existence of methods like awaitBodyOrNull (I'm using Kotlin).
Am I missing/misunderstanding something here? I'm constructing my mock by just doing MockServerRequest.builder().build() (the methods under test don't care about anything other than the body). Is this class perhaps not actually meant to be used on its own? I'm not finding anyone else asking about this so I feel like I must be overlooking something.
For now I'll work around this by just making my own mock.

MockServerRequest.Builder expects you to give it a body already wrapped in a Mono. It doesn't do any wrapping for you. So mocking an empty request is done with MockServerRequest.builder().body(Mono.empty<TestDto>()).

Related

What are the differences of Flux<T>, Flux<ResponseEntity<T>>, ResponseEntity<Flux<T>> as return type in Spring WebFlux?

I often see three different response return types: Flux<T>, ResponseEntity<Flux<T>>, and Flux<ResponseEntity<T>> in MVC style controllers using Spring WebFlux. The documentation explains the difference between ResponseEntity<Flux<T>> and Flux<ResponseEntity<T>>. Does Spring automatically wrap Flux<T> as either ResponseEntity<Flux<T>> or Flux<ResponseEntity<T>>? if yes, which one?
Moreover, how to decide which one to return, ResponseEntity<Flux<T>> or Flux<ResponseEntity<T>>? What situation or use case would call for using one over the other?
And, from a webclient's point of view, are there any significant differences when consuming the two types of response?
Does Spring automatically wrap Flux as either
ResponseEntity<Flux> or Flux<ResponseEntity>? if yes, which one?
Spring will automatically wrap that Flux as a ResponseEntity<Flux>. For example if you have a web endpoint as follows
#GetMapping("/something")
public Flux handle() {
doSomething()
}
And if you are consuming from a WebClient, you can retrieve your response as either ResponseEntity<Flux<T>> or Flux<T>. There is no default, but I would think it's good practice to retrieve only Flux unless you explicitly need something from the ResponseEntity. The Spring doc has good examples of this.
You actually can consume it as a Flux<ResponseEntity<T>>, but this would only be applicable for more complex use cases.
Moreover, how to decide which one to return, ResponseEntity<Flux>
or Flux<ResponseEntity>? What situation or use case would call for
using one over the other?
It really depends on your use case.
Returning ResponseEntity<Flux<T>> is saying something like,
I am returning a Response of a Collection of type T objects.
Where Flux<ResponseEntity<T>> is saying something more like
I am returning a Collection of Responses, where the responses have an entity of type T.
Again, I think in most use cases returning just Flux<T> makes sense (This is equivalent to returning ResponseEntity<Flux<T>>)
And finally
And, from a webclient's point of view, are there any significant
differences when consuming the two types of response?
I think what you're trying to ask is whether you should be using ResponseEntity<Flux<T>> or Mono<ResponseEntity<T>> when consuming from the WebClient. And the spring doc answers this question quite elegantly
ResponseEntity<Flux> make the response status and headers known
immediately while the body is provided asynchronously at a later
point.
Mono<ResponseEntity> provides all three — response status, headers,
and body, asynchronously at a later point. This allows the response
status and headers to vary depending on the outcome of asynchronous
request handling.

Ignore an Empty Request Body?

After writing tests for my REST API (built using Spring Boot), I realised that, even when the request body is not used (see below), calling the endpoint with a request body succeeds–effectively, Spring ignores the body.
This is not a huge issue, but I was wondering what philosophy I should approach this with:
Should I fail when passed an unexpected body (when do not expect any)?
If so, is this configurable in Spring so that there is strict checking of body/parameters?
Finally, beyond personal preference and/or experience, is there a good way of deciding this, or should I simply use 'if it isn't broken, don't fix it' as my mantra?
#PatchMapping(value = "/products/{pid}/sell")
public TxDTO sell(#NotBlank #PathVariable("pid") String pid,
#NotNull #RequestParam Float price)
I think you shouldn't think too much into this. Technically, ignoring the unexpected body doesn't violate any software development principles. Even though this might be something that makes you feel uncomfortable personally in the context of your project, you might want to consider other scenarios where there's a filter or servlet sitting in front of your #RestController doing some additional stuff you're not aware of.
The point is this is not a feature you should turn off globally nor it is worth spending time implementing custom code to turn it off locally for a single endpoint :).

Can I fake calling methods in Ruby tests?

I'm running some tests on my Ruby code, but the method I'm testing calls a function in an external library responsible for sending push notifications. I want the calls it makes to be 'faked', so they don't actually get called. It'd also be helpful if they could return a standard response, or yield with a standard response. Is there any way to do this?
Sure you can fake calling methods in Ruby tests. What you are looking for is creating so called mock code. It is entirely possible to return anything you want from such mock code.
You can create an identifier in Ruby which shadows another one - so for example you can create your own function shadowing one already existing in a library.
Google for the items written above in bold or ask more specific question, if needed.
The VCR gem makes it very easy to save your test suite's HTTP interactions and run them deterministically. That would be my suggested approach.
You can also, as others have pointed out, stub the method you are calling and manually specify its response. If you were using rspec, this would mean to add a line above the HTTP call in the test. Something along the lines of:
allow(Pusher).to receive(:message).and_return( "An object of your liking" )

EasyMock aware debugger in Intellij?

Maybe this is counterproductive, I don't know, but right now I am in need of a debugger in IntelliJ that are aware of EasyMock mocks and especially what the mocks methods actually returns.
For example, I have a transport interface ITransport, which has some methods that had to be mocked, and where I only want some of methods returning something. E.g.
ITransport myTransport = createMock(ITransport.class);
I want myTransport.getID() to return a mocked ID 10.
expect(myTransport.getID()).andReturn(10);
With ID 10 I want a method to be invoked once,
expect(myTransport.publish(any(...)));
expectLastCall.once();
Something in the transport class breaks and myTransport isn't called, and my test fails. Know I just want to step through the code with the debugger to check why my test fails. So I add a breakpoint to verify the values of the mocked myTransport object. But they all say "null", even the ID. So I assume, with some brief investigation, that the cause of this is the EasyMock mock class, it doesn't really update the object with value (which sounds reasonable) and instead returns the mocked value at runtime when the method is called.
So, are there any mock aware debuggers for IntelliJ that lets me see which value the method will eventually return.
Yes, and before I receive responses saying that "The debugger is not required if you write unit tests for everything", I just want to state that I know about that. And this is legacy code, or at least code that wasn't written with testing in mind.
This may not be what you're looking for... but it feels like the problem is more on the debugging approach.
A mock object is really just that - a mock - meaning it's a fake empty object that doesn't do anything unless you specifically tell it. When your debugger inspects the mock object, it won't find any values that you did not specifically program it to return. It's not meant to hold values.
EasyMock has an argument capture feature, but since you just want it for debugging, this is probably the wrong approach. Mockito has a spying feature that could be suitable for what you want, but it would involve additional mock-programming statements.
I would say the easiest approach would be to implement your own ITransport just for use in your test class. That way you can implement getID() to always return 10 and put in an assert statement inside your publish(). And you can implement whatever other methods you need in order to capture additional data for debugging purposes. And you get to keep this test-only ITransport for either shared use or future debugging needs.
Indeed, the methods are mocked but the internal implementation of the class is left to itself.
Usually, you don't need to know what is returned since you're the one who recorded it in the first place.
You can also evaluate myTransport.getID() in your debugger. But doing this will consume the expectations.
However, it seems like a good idea to be able to list the all current pending expectations on a mock. And maybe to have a peek function. You can request such features on the EasyMock bug tracker: http://jira.codehaus.org/browse/EASYMOCK

TDD and mocking

First of all, I have to say, I'm new to mocking. So maybe I'm missing a point.
I'm also just starting to get used to the TDD approach.
So, in my actual project I'm working on a class in the business layer, while the data layer has yet to be deployed. I thought, this would be a good time to get started with mocking. I'm using Rhino Mocks, but I've come to the problem of needing to know the implementation details of a class before writing the class itself.
Rhino Mocks checks if alle the methods expected to be called are actually called. So I often need to know which mocked method is being called by the tested method first, even though they could be called in any order. Because of that I'm often writing complicated methods before I test them, because then I know already in which order the methods are being called.
simple example:
public void CreateAandB(bool arg1, bool arg2) {
if(arg1)
daoA.Create();
else throw new exception;
if(arg2)
daoB.Create();
else throw new exception;
}
if I want to test the error handling of this method, I'd have to know which method is being called first. But I don't want to be bugged about implementation details when writing the test first.
Am I missing something?
You have 2 choices. If the method should result in some change in your class the you can test the results of your method instead. So can you call CreateAandB(true,false) then then call some other method to see if the correct thing was created. In this situation your mock objects will probably be stubs which just provide some data.
If the doaA and doaB are objects which are injected into your class that actually create data in the DB or similar, which you can't verify the results of in the test, then you want to test the interaction with them, in which case you create the mocks and set the expectations, then call the method and verify that the expectations are met. In this situation your mock objects will be mocks and will verify the expected behaviour.
Yes you are testing implementation details, but your are testing the details of if your method is using its dependencies correctly, which is what you want to test, not how it is using them, which are the details you are not really interested in.
EDIT
IDao daoA = MockRepository.GenerateMock<IDao>(); //create mock
daoA.Expect(dao=>dao.Create); //set expectation
...
daoA.VerifyExpectations(); //check that the Create method was called
you can ensure that the expectations happen in a certain order, but not using the AAA syntax I believe (source from 2009, might have changed since,EDIT see here for an option which might work), but it seems someone has developed an approach which might allow this here. I've never used that and can't verify it.
As for needing to know which method was called first so you can verify the exception you have a couple of choices:
Have a different message in your exception and check that to determine which exception was raised.
Expect a call to daoA in addition to expecting the exception. If you don't get the call to daoA then the test fails as the exception must have been the first one.
Often times you just need fake objects, not mocks. Mock objects are meant to test component interaction, and often you can avoid this by querying the state of SUT directly. Most practical uses of mocks are to test interaction with some external system (DB, file system, webservice, etc.), and for other things you should be able to query system state directly.

Resources