There is a type of statement in java that I could not understand or even find anything about through googling. I would like to share an example which I wrote but without understanding the language structure :
MvcResult result = this.mockMvc.perform(MockMvcRequestBuilders.post("/user_sessions/first")
.contentType(MediaType.APPLICATION_JSON)
.content("{\"username\":\""+username+"\",\"password\":\""+password+"\"}"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andReturn();
I don't understand what contentType , content, andExpect and andReturn are. They are obviously functions, but how can I call them like this. What class do they belong to? Overally I am very confused with the structure here.
What you are seeing here is called a fluent interface. A fluent interface is a mechanism to help improve the readability of code by cascading method calls. When you create a method the return value is that of the class, so in pseudo code this would be something like -
class Foo {
private String baa;
private String moo;
public Foo setBaa( String baa ) {
this.baa = baa;
return this;
}
public Foo setMoo( String moo ) {
this.moo = moo;
return this;
}
}
Note: the use of this as a return value to show that we are returning our current foo instance. This would allow the folliwng behaviour -
Foo test = new Foo();
test.setBaa( "baa" ).setMoo( "moo" );
If you would like more information on Fluent interfaces please have a look at http://en.wikipedia.org/wiki/Fluent_interface which gives a fairly in depth explanation.
This is done for better readability. You could also write it as:
result = this.mockMvc.perform(MockMvcRequestBuilders.post("/user_sessions/first").contentType(MediaType.APPLICATION_JSON).content("{\"username\":\""+username+"\",\"password\":\""+password+"\"}")).andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
All those methods return objects and the following methods are invoked on the returned objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With