Skip to content

Instantly share code, notes, and snippets.

@icchan
Created October 7, 2015 07:17
Show Gist options
  • Save icchan/2a742496ab0bb4157c06 to your computer and use it in GitHub Desktop.
Save icchan/2a742496ab0bb4157c06 to your computer and use it in GitHub Desktop.
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
* Sample tests using mockito
*
* @author ian.chen
*/
public class SampleControllerTest {
// a controller to test
private MyController controller;
private MyService mockService;
/**
* Will run before each test method
*/
@Before
public void setUp() {
// create a controller
controller = new MyController();
// create a mock of the backend
mockService = Mockito.mock(MyService.class);
// inject the mock
controller.setService(mockService);
// TODO perform other initialization here
}
/**
* Test happy case
*/
@Test
public void sampleTest() throws Exception {
// define the behaviour of the backend
when(mockService.getMessage()).thenReturn("I am a mock");
// Test the method
ResponseEntity<String> response = controller.handleRequest();
// check it was a 200
assertThat(response.getStatusCode(), equalTo(HttpStatus.OK));
// check the body is the the expected value
assertThat(response.getBody(), equalTo("I am a mock"));
}
/**
* Test error case
*/
@Test
public void sampleError() throws Exception {
// tell the backend to throw an exception
when(mockService.getMessage())
.thenThrow(new IOException());
// This should throw an exception
ResponseEntity<String> response = controller.handleRequest();
// check an error response was received
assertThat(response.getStatusCode(), equalTo(HttpStatus.INTERNAL_SERVER_ERROR));
}
/**
* Test that an exception is thrown.
*/
@Test(expected = RuntimeException.class)
public void sampleThrownException() throws Exception {
// tell the backend to throw an uncaught exception
when(mockService.getMessage())
.thenThrow(new RuntimeException());
// This should throw an exception
controller.handleRequest();
}
/***************************
* Example classes to test *
***************************/
// a example of a service which needs to be injected
interface MyService {
public String getMessage() throws IOException;
}
// a example of a controller to test
class MyController {
private MyService service;
public void setService(MyService service) {
this.service = service;
}
public ResponseEntity<String> handleRequest() {
try {
return new ResponseEntity<String>(service.getMessage(), HttpStatus.OK);
} catch (IOException e) {
return new ResponseEntity<String>("An exception was thrown", HttpStatus.INTERNAL_SERVER_ERROR);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment