Skip to content

Instantly share code, notes, and snippets.

@macg33zr
Last active August 29, 2015 14:27
Show Gist options
  • Save macg33zr/6cd1f77b0d92db8e1fb3 to your computer and use it in GitHub Desktop.
Save macg33zr/6cd1f77b0d92db8e1fb3 to your computer and use it in GitHub Desktop.
Spring Boot Mocking Groovy REST Controller
/**
*
* How to Unit test Spring Boot REST Controller with mocks
*
* Requires Groovy mockito support dependency in build.gradle:
*
* testCompile("org.springframework.boot:spring-boot-starter-test")
*
* Otherwise mocks crash with NPE..
* See https://github.com/cyrusinnovation/mockito-groovy-support
*
*/package demo
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType
import org.springframework.test.context.web.WebAppConfiguration
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations
import org.springframework.web.context.WebApplicationContext;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@WebAppConfiguration
class HelloControllerTests {
@Mock
private HelloService helloService
@InjectMocks
private HelloController helloController
protected MockMvc mvc;
@Autowired
protected WebApplicationContext webApplicationContext;
@Before
void beforeEachTest() {
MockitoAnnotations.initMocks(this)
mvc = MockMvcBuilders.standaloneSetup(helloController).build()
}
@Test
void testHello() {
Hello data = new Hello([name:"Test says hello"])
when(helloService.doHello()).thenReturn(data)
String uri = "/hello";
MvcResult result = mvc.perform( MockMvcRequestBuilders.get(uri).accept(MediaType.APPLICATION_JSON)).andReturn();
String content = result.getResponse().getContentAsString();
int status = result.getResponse().getStatus();
verify(helloService, times(1)).doHello();
assert status == 200
assert content.trim().size() > 0
assert content.trim() == '{"name":"Test says hello"}'
println content
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment