Skip to content

Instantly share code, notes, and snippets.

@matsev
matsev / CustomResponseEntityExceptionHandler.java
Last active January 16, 2023 06:04
Generic response error handling using @ControllerAdvice
@ControllerAdvice
public class CustomResponseEntityExceptionHandler extends ResponseEntityExceptionHandler {
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
List<ObjectError> globalErrors = ex.getBindingResult().getGlobalErrors();
List<String> errors = new ArrayList<>(fieldErrors.size() + globalErrors.size());
String error;
for (FieldError fieldError : fieldErrors) {
@matsev
matsev / GetTestUserAsJson.java
Created September 8, 2012 06:13
Spring Controller Tests 2.0
@Test
public void shouldGetTestUserAsJson() throws Exception {
mockMvc
.perform(get("/user/0")
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON))
.andExpect(jsonPath("name", is("Test User")))
.andExpect(jsonPath("email", is("test.user@somewhere.com")));
}
@matsev
matsev / ErrorMessage.java
Last active September 28, 2018 16:22
Enhanced error feedback from a Spring Controller
@XmlRootElement
public class ErrorMessage {
private List<String> errors;
public ErrorMessage() {
}
public ErrorMessage(List<String> errors) {
this.errors = errors;
@RequestMapping(method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
@ResponseStatus(HttpStatus.CREATED)
void create(@RequestBody @Valid User user, HttpServletRequest request, HttpServletResponse response) {
long userId = userService.create(user);
String location = ServletUriComponentsBuilder.fromRequestUri(request).path("/{userid}")
.build()
.expand(userId).toUriString();
response.addHeader("Location", location);
}
@matsev
matsev / ConstructorExample.java
Created February 18, 2012 09:26
Mockito and Dependency Injection
public class Example {
private Delegate delegate;
Example(Delegate delegate) {
this.delegate = delegate;
}
public void doIt() {
delegate.execute();
@matsev
matsev / Delegate.java
Created December 3, 2011 20:02
Using Mock Obects in Spring Integration Tests
package com.jayway.example;
public interface Delegate {
String doSomething();
String doSomethingElse();
}
@matsev
matsev / BeanWiringTest.java
Created November 27, 2011 14:12
Creating Spring FactoryBeans for Mock Objects
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("failing-mockito-config.xml")
public class BeanWiringTest {
@Autowired
SomeClass someClass;
@Autowired
SomeDependency someDependencyMock;