How do I test a custom Spring Boot Actuator endpoint? - java

I have a spring boot actuator and WebMvc test isn't working. It returns an empty body. How would I test this?
#Configuration
#ManagementContextConfiguration
public class TestController extends AbstractMvcEndpoint
{
public TestController()
{
super( "/test", false, true );
}
#GetMapping( value = "/get", produces = MediaType.APPLICATION_JSON_VALUE )
#ResponseBody
public OkResponse getInfo() throws Exception
{
return new OkResponse( 200, "ok" );
}
#JsonPropertyOrder( { "status", "message" } )
public static class OkResponse
{
#JsonProperty
private Integer status;
#JsonProperty
private String message;
public OkResponse(Integer status, String message)
{
this.status = status;
this.message = message;
}
public Integer getStatus()
{
return status;
}
public String getMessage()
{
return message;
}
}
}
When I try to test it with the below, it doesn't work. I get an empty body in the return.
#RunWith( SpringJUnit4ClassRunner.class )
#DirtiesContext
#WebMvcTest( secure = false, controllers = TestController.class)
#ContextConfiguration(classes = {TestController.class})
public class TestTestController
{
private MockMvc mockMvc;
private ObjectMapper mapper;
#Autowired
private WebApplicationContext webApplicationContext;
#Before
public void setup()
{
//Create an environment for it
mockMvc = MockMvcBuilders.webAppContextSetup( this.webApplicationContext )
.dispatchOptions( true ).build();
mapper = new ObjectMapper();
}
#SpringBootApplication(
scanBasePackageClasses = { TestController.class }
)
public static class Config
{
}
#Test
public void test() throws Exception
{
//Get the controller's "ok" message
String response = mockMvc.perform(
get("/test/get")
).andReturn().getResponse().getContentAsString();
//Should be not null
Assert.assertThat( response, Matchers.notNullValue() );
//Should be equal
Assert.assertThat(
response,
Matchers.is(
Matchers.equalTo(
"{\"status\":200,\"message\":\"ok\"}"
)
)
);
}
}

Here's a test I wrote to do something like what you are talking about. This test validates that our only the actuator endpoints we want to expose are available.
This is using SpringBoot 1.5.
I found the question here helpful: Unit testing of Spring Boot Actuator endpoints not working when specifying a port.
#RunWith(SpringRunner.class)
#SpringBootTest
#TestPropertySource(properties = {
"management.port="
})
public class ActuatorTests {
#Autowired
private WebApplicationContext context;
#Autowired
private FilterChainProxy springSecurityFilterChain;
private MockMvc mvc;
#Before
public void setup() {
context.getBean(MetricsEndpoint.class).setEnabled(true);
mvc = MockMvcBuilders
.webAppContextSetup(context)
.alwaysDo(print())
.apply(SecurityMockMvcConfigurers.springSecurity(springSecurityFilterChain))
.build();
}
#Test
public void testHealth() throws Exception {
MvcResult result = mvc.perform(get("/health")
.with(anonymous()))
.andExpect(status().is2xxSuccessful())
.andReturn();
assertEquals(200, result.getResponse().getStatus());
}
#Test
public void testRestart() throws Exception {
MvcResult result = mvc.perform(get("/restart")
.with(anonymous()))
.andExpect(status().is3xxRedirection())
.andReturn();
assertEquals(302, result.getResponse().getStatus());
assertEquals("/sso/login", result.getResponse().getRedirectedUrl());
}
}

Related

Unit Testing rest controller with #AuthenticationPrincipal

I am developing a rest api with spring boot and spring security.
the code looks like so:
#RestController
#RequestMapping(path = "/api")
#PreAuthorize("isAuthenticated()")
public class RestController {
#GetMapping(path = "/get", produces = "application/json")
public ResponseEntity<InDto> get(
#AuthenticationPrincipal final CustomUser user) {
// ...
return ResponseEntity.ok(outDto);
}
}
public class CustomUser {
// does not inherit from UserDetails
}
public class CustomAuthenticationFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(
#NonNull final HttpServletRequest request,
#NonNull final HttpServletResponse response,
#NonNull final FilterChain filterChain)
throws ServletException, IOException {
if (/* condition */) {
// ...
final CustomUser user = new CustomUser(/* parameters */);
final Authentication authentication =
new PreAuthenticatedAuthenticationToken(user, "", new ArrayList<>());
SecurityContextHolder.getContext().setAuthentication(authentication);
}
filterChain.doFilter(request, response);
}
}
I would like to unit test the RestController class ideally without the security feature but I don't know how to inject a specific CustomUser object during test.
I have tried to manually add a user to the security context before each test (see below) but the user injected into the controller during test is not the mocked on.
#WebMvcTest(RestController.class)
#AutoConfigureMockMvc(addFilters = false)
class RestControllerTest {
#Autowired private MockMvc mockMvc;
private CustomerUser userMock;
#BeforeEach
public void skipSecurityFilter() {
userMock = Mockito.mock(CustomUser.class);
SecurityContextHolder.setContext(SecurityContextHolder.createEmptyContext());
final Authentication auth = new PreAuthenticatedAuthenticationToken(userMock, null, List.of());
SecurityContextHolder.getContext().setAuthentication(auth);
}
#Test
void test() {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/get")
.contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk());
}
}
What is wrong? How to inject the specific userMock into the controller to perform the test?
EDIT to test with #WithMockCustomUser
as suggested in the doc https://docs.spring.io/spring-security/reference/servlet/test/method.html#test-method-withsecuritycontext i have updated the test to:
#Retention(RetentionPolicy.RUNTIME)
#WithSecurityContext(factory = WithMockCustomUserSecurityContextFactory.class)
public #interface WithMockCustomUser {
}
#Service
public class WithMockCustomUserSecurityContextFactory
implements WithSecurityContextFactory<WithMockCustomUser> {
#Override
public SecurityContext createSecurityContext(final WithMockCustomUser customUser) {
final SecurityContext context = SecurityContextHolder.createEmptyContext();
final Authentication auth =
new PreAuthenticatedAuthenticationToken(Mockito.mock(IUser.class), null, List.of());
context.setAuthentication(auth);
return context;
}
}
#WebMvcTest(RestController.class)
#AutoConfigureMockMvc(addFilters = false)
class RestControllerTest {
#Autowired private MockMvc mockMvc;
private CustomerUser userMock;
#BeforeEach
public void skipSecurityFilter() {
userMock = Mockito.mock(CustomUser.class);
}
#Test
#WithMockCustomUser
void test() {
mockMvc.perform(
MockMvcRequestBuilders.get("/api/get")
.contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk());
}
}
but the user object in the controller is still not the mock (created in the factory)
I rewrote the test to initialise the security context within the test
#WebMvcTest(RestController.class)
#AutoConfigureMockMvc
#Import(value = {
CustomAuthenticationFilter.class
})
class RestControllerTest {
#Autowired private MockMvc mockMvc;
private CustomerUser userMock;
#BeforeEach
public void skipSecurityFilter() {
userMock = Mockito.mock(CustomUser.class);
}
#Test
void test() {
PreAuthenticatedAuthenticationToken(userMock, null, List.of());
SecurityContextHolder.getContext().setAuthentication(auth);
mockMvc.perform(MockMvcRequestBuilders.get("/api/get").contentType(MediaType.APPLICATION_JSON)).andExpect(MockMvcResultMatchers.status().isOk());
}
}
and it works.
Not sure exactly why the it does not work with the #BeforeEach.

No mapping for request with mockmvc

Currently struggling with problem when I get 'mapping error for request' with following controller/test configuration.
Controller:
#Slf4j
#Validated
#RestController
#RequiredArgsConstructor
public class AdtechController {
private final AdtechService adtechService;
#PostMapping(value = "/subscriber/session")
public ResponseEntity<ResponseDto> submitSession(#RequestBody RequestDto requestDto) {
log.trace("execute submitSession with {}", requestDto);
ResponseDtoresponse = adtechService.submitSession(requestDto);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#ExceptionHandler(AdtechServiceException.class)
public ResponseEntity<AdtechErrorResponse> handleAdtechServiceException(AdtechServiceException e) {
return new ResponseEntity<>(new AdtechErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Test:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
#SpringJUnitConfig({AdtechTestConfig.class})
public class AdtechControllerTest {
private static final ObjectMapper OBJECT_MAPPER = JsonUtil.getJackson();
#Autowired
private MockMvc mockMvc;
#Test
public void testSubmitSession() throws Exception {
RequestDto requestDto = new RequestDto ();
requestDto.setKyivstarId("1123134");
requestDto.setMsisdn("123476345242");
requestDto.setPartnerId("112432523");
requestDto.setPartnerName("125798756");
String request = OBJECT_MAPPER.writeValueAsString(requestDto);
System.out.println("REQUEST: " + request);
String response = OBJECT_MAPPER.writeValueAsString(new ResponseDto("123"));
System.out.println("RESPONSE: " + response);
mockMvc.perform(post("/subscriber/session")
.content(MediaType.APPLICATION_JSON_VALUE)
.content(request))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString(response)));
}
}
Configuration:
#Configuration
public class AdtechTestConfig {
#Bean
public AdtechService adtechTestService() {
return requestDto -> new AdtechResponseDto("123");
}
}
After test execution I get No mapping for POST /subscriber/session
The reason for the struggle is that my code from other modules with the same configuration works fine. Can somebody point out what am I missing ? Thanks in advance!
Apparently you are loading a configuration class to mock beans, this interferes with the other parts of Spring Boot and probably leads to partially loading your application. I suspect only the mocked service is available.
Instead of the test configuration use #MockBean to create a mock for the service and register behaviour on it.
#SpringBootTest
#AutoConfigureMockMvc
public class AdtechControllerTest {
private static final ObjectMapper OBJECT_MAPPER = JsonUtil.getJackson();
#Autowired
private MockMvc mockMvc;
#MockBean
private AdtechService mockService;
#BeforeEach
public void setUp() {
when(mockService.yourMethod(any()).thenReturn(new AdtechResponseDto("123"));
}
#Test
public void testSubmitSession() throws Exception {
// Your original test method
}
}
If the only thing you want to test is your controller you might also want to consider using #WebMvcTest instead of #SpringBootTest.
#WebMvcTest(AdTechController.class)
public class AdtechControllerTest {
private static final ObjectMapper OBJECT_MAPPER = JsonUtil.getJackson();
#Autowired
private MockMvc mockMvc;
#MockBean
private AdtechService mockService;
#BeforeEach
public void setUp() {
when(mockService.yourMethod(any()).thenReturn(new AdtechResponseDto("123"));
}
#Test
public void testSubmitSession() throws Exception {
// Your original test method
}
}
This will load a scaled-down version of the context (only the web parts) and will be quicker to run.
try this:
#Slf4j
#Validated
#RestController
#RequiredArgsConstructor
public class AdtechController {
private AdtechService adtechService;
public AdtechController (AdtechService adtechService) {
this.adtechService= adtechService;
}
#PostMapping(value = "/subscriber/session")
public ResponseEntity<ResponseDto> submitSession(#RequestBody RequestDto requestDto) {
log.trace("execute submitSession with {}", requestDto);
ResponseDtoresponse = adtechService.submitSession(requestDto);
return new ResponseEntity<>(response, HttpStatus.OK);
}
#ExceptionHandler(AdtechServiceException.class)
public ResponseEntity<AdtechErrorResponse> handleAdtechServiceException(AdtechServiceException e) {
return new ResponseEntity<>(new AdtechErrorResponse(HttpStatus.INTERNAL_SERVER_ERROR.value(), e.getMessage()), HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Test:
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
#SpringJUnitConfig({AdtechTestConfig.class})
public class AdtechControllerTest {
private static final ObjectMapper OBJECT_MAPPER = JsonUtil.getJackson();
#Autowired
private MockMvc mockMvc;
#Autowired
private AdtechService adtechService;
#Before
public void setUp() {
MockitoAnnotations.initMocks(this);
this.mvc = MockMvcBuilders.standaloneSetup(new AdtechController(adtechService)).build();
}
#Test
public void testSubmitSession() throws Exception {
RequestDto requestDto = new RequestDto ();
requestDto.setKyivstarId("1123134");
requestDto.setMsisdn("123476345242");
requestDto.setPartnerId("112432523");
requestDto.setPartnerName("125798756");
String request = OBJECT_MAPPER.writeValueAsString(requestDto);
System.out.println("REQUEST: " + request);
String response = OBJECT_MAPPER.writeValueAsString(new ResponseDto("123"));
System.out.println("RESPONSE: " + response);
mockMvc.perform(post("/subscriber/session")
.content(MediaType.APPLICATION_JSON_VALUE)
.content(request))
.andDo(print())
.andExpect(status().isOk())
.andExpect(content().string(containsString(response)));
}
}
Is the AdtechTestConfig.class introducing the /ad-tech path segment in to your test request? If so, this is why your test is trying the path /ad-tech/subscriber/session instead of /subscriber/session.
If this is actually the correct uri, then you may add #RequestMapping to the controller like below or just to the post method itself
#Slf4j
#Validated
#RestController
#RequestMapping("/ad-tech")
#RequiredArgsConstructor
public class AdtechController {
private final AdtechService adtechService;
#PostMapping(value = "/subscriber/session")
public ResponseEntity<ResponseDto> submitSession(#RequestBody RequestDto requestDto) {
...

Spring MVC Mockito Test returning 406 error instead of 200

So I am working with a working UI, and using a DB2 database. I am trying to run unit testing on the controller/service/dao layers and I am using mockito and junit to test. Here are the pieces of each layer:
Measures.java
#Controller
#RequestMapping(value = "/measures"})
public class Measures {
#Resource
private CheckUpService checkUpService;
public void setCheckUpService(CheckUpService checkUp) {
this.checkUpService = checkUpService;
}
#RequestMapping(value = "/eligibility/{userId}/{effDate}/{stageInd}", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Model> findEligibility(#PathVariable int userId, #PathVariable String effDate, #PathVariable String stageInd) throws Exception
{
List<Model> result = new ArrayList<Model>();
if (stageInd.equals("stage"))
{
result = checkUpService.findEligibilityStage(userId, effDate);
}
if (stageInd.equals("prod"))
{
result = checkUpService.findEligibility(userId, effDate);
}
return result;
}
...
}
CheckUpService.java
public class CheckUpService {
#Resource
EligibilityDao eligDao;
public List<Model> findEligibility(int userId, String effDate) throws Exception
{
return eligDao.findEligibility(userId, effDate, db_table);
}
}
EligibilityDao.class
public class EligibilityDao {
public List<Model> findEligibility(int userId, String effDate, String table) throws Exception
{
// uses some long sql statement to get some information db2 database and
// jdbctemplate helps return that into a list.
}
}
Here is the controller test that I am trying to do, I've spent about 10 hours on this and I really can't figure out why it's giving me a 406 error instead of 200.
ControllerTest.java
#EnableWebMvc
#WebAppConfiguration
public class ControllerTest {
#Autowired
private Measures measures;
#Autowired
private WebApplicationContext webApplicationContext;
private MockMvc mockMvc;
private List<Model> findEligibility() {
List<Model> list = new ArrayList<>();
Model test_model = new Model();
test_model.setUserId(99);
test_model.setCreateID("testUser");
test_model.setEffDate("2020-07-30");
list.add(test_model);
return list;
}
#Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
#Test
public void test_find() throws Exception {
CheckUpService checkUpService = mock(CheckUpService.class);
when(checkUpService.findEligibility(99, "2020-07-30")).thenReturn(findEligibility());
measures.setCheckUpService(checkUpService);
String URI = "/measures/eligibility/99/2020-07-30/prod";
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI).contentType(MediaType.APPLICATION_JSON).accept(MediaType.APPLICATION_JSON);
MvcResult handle = mockMvc.perform(requestBuilder).andReturn();
// MvcResult handle = mockMvc.perform(requestBuilder).andExpect(status().isOk()).andReturn();
MvcResult result = mockMvc.perform(asyncDispatch(handle)).andExpect(status().isOk()).andReturn();
// assertThat(result.getResponse().getContentAsString()).isEqualTo(findEligibility());
}
}
The MvcResult result is what is throwing the "StatusExpected <200> but was <406>" error in junit and i'm going mad on why it is. Another issue is that, if you can see, I commented out the handle with the .andExpect(status().isOk()) and that one was also throwing the same issue. Is it something i'm setting up wrong with the test or something?
I could not reproduce your issue. However, I got this working.
So, no big changes to the Controller, but I removed the field injection in favor of constructor injection.
#Controller
#RequestMapping(value = "/measures")
public class Measures {
private final CheckUpService checkUpService;
public Measures(CheckUpService checkUpService) {
this.checkUpService = checkUpService;
}
#RequestMapping(value = "/eligibility/{userId}/{effDate}/{stageInd}", method = RequestMethod.POST, produces = "application/json")
public #ResponseBody List<Model> findEligibility(#PathVariable int userId, #PathVariable String effDate, #PathVariable String stageInd) throws Exception {
List<Model> result = new ArrayList<>();
if (stageInd.equals("stage")) {
result = checkUpService.findEligibility(userId, effDate);
}
if (stageInd.equals("prod")) {
result = checkUpService.findEligibility(userId, effDate);
}
return result;
}
}
The same for the service class.
#Service
public class CheckUpService {
private final EligibilityDao dao;
public CheckUpService(EligibilityDao dao) {
this.dao = dao;
}
public List<Model> findEligibility(int userId, String effDate) throws Exception {
return dao.findEligibility(userId, effDate, "demo value");
}
}
and here's the test. Instead of initializing the MockMvc and injecting the web context, I inject MockMvc. Also, using #MockBean, you can inject mocks. So, I removed the mock creation from the test method to the initialization part.
#RunWith(SpringRunner.class)
#SpringBootTest
#AutoConfigureMockMvc
public class MeasuresTest {
#Autowired
private MockMvc mockMvc;
#MockBean
private CheckUpService service;
#Test
public void test_find() throws Exception {
Model model = new Model(99, "2020-08-02", "2020-07-30");
when(service.findEligibility(99, "2020-07-30"))
.thenReturn(Collections.singletonList(model));
String URI = "/measures/eligibility/99/2020-07-30/prod";
MockHttpServletRequestBuilder requestBuilder = MockMvcRequestBuilders.post(URI)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON);
final MvcResult mvcResult = mockMvc.perform(requestBuilder)
.andExpect(status().isOk()).andReturn();
final String json = mvcResult.getResponse().getContentAsString();
final List<Model> models = new ObjectMapper().readValue(json, new TypeReference<>() {
});
Assert.assertEquals(1, models.size());
Assert.assertEquals(model, models.get(0));
}
}
In the post, I could not find any reason why you used asyncDispatch, so I just did not use it.

When try to test post() rest endpoint see: json can not be null or empty

If I try to test the post() endpoint, I see:
java.lang.AssertionError: No value at JSON path "$.firstName"
Caused by: java.lang.IllegalArgumentException: json can not be null or empty
But with the test for the get() all work fine.
And in the postTest() the result for status is correct.
Where is my mistaker?
Is it correct way to test the rest controller in this style?
#RunWith(MockitoJUnitRunner.Silent.class)
public class Temp {
private final Employee successfullyRegisteredEmployee = new Employee(2L, "Iven");
private final Employee employeeGetById = new Employee(2L, "Iven");
#Mock
private EmployeeServiceImpl serviceMock;
private MockMvc mockMvc;
#Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.standaloneSetup(new EmployeeControllerImpl( serviceMock))
.build();
}
#Test
public void getTest() throws Exception {
when(serviceMock.getEmployee(2L)).thenReturn(employeeGetById);
mockMvc.perform(get("/employee/get/2"))
.andExpect(status().is(200))
.andExpect(content().json(("{'firstName':'Iven'}")));
verify(serviceMock).getEmployee(2L);
}
#Test
public void postTest() throws Exception {
String json = "{\n" +
" \"firstName\": \"Iven\"\n"
"}";
when(serviceMock.register(employeeForRegister)).thenReturn(successfullyRegisteredEmployee);
mockMvc.perform( MockMvcRequestBuilders
.post("/employee/register")
.content(json)
.contentType(MediaType.APPLICATION_JSON)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().is(201))
.andExpect(jsonPath("$.firstName", Matchers.is("Iven")));
}
}
#RestController
#RequestMapping("/employee")
public class EmployeeControllerImpl implements EmployeeController {
private final EmployeeService service;
public EmployeeControllerImpl(EmployeeService service) {
this.service = service;
}
#PostMapping(path = "/register",
consumes = "application/json",
produces = "application/json"
)
public ResponseEntity<Employee> registerEmployee(#Valid #RequestBody Employee employee) {
Employee registeredEmployee = service.register(employee);
return ResponseEntity.status(201).body(registeredEmployee);
}
}
Seems like problem could be with when(serviceMock.register(employeeForRegister)).thenReturn(successfullyRegisteredEmployee);.
Did you try to have breakpoint on return ResponseEntity.status(201).body(registeredEmployee); to check if registeredEmployee is actually filled?
If it's empty then try replacing mock with when(serviceMock.register(any())).thenReturn(successfullyRegisteredEmployee); and if it works that means either equals() method is not overridden for Employee or comparison just fails.

spring boot controller test, mockMov doesn't mock

I use Spring MVC and Spring boot to write a Restful service. This code works fine through postman.While when I do the unit test for the controller to accept a post request, the mocked myService will always initialize itself instead of return a mocked value defined by when...thenReturn... I use verify(MyService,times(1)).executeRule(any(MyRule.class)); and it shows the mock is not used.
I also tried to use standaloneSetup for mockMoc, but it complains it can't find the mapping for the path "/api/rule".
Could anybody help to figure out the problem?
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(classes = Application.class)
#WebAppConfiguration
public class MyControllerTest {
#Mock
private MyService myService;
#InjectMocks
private MyController myRulesController;
private MockMvc mockMvc;
#Autowired
private WebApplicationContext wac;
#Before
public void setup() {
MockitoAnnotations.initMocks(this);
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
#Test
public void controllerTest() throws Exception{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
Long userId=(long)12345;
MyRule happyRule = MyRule.createHappyRule(......);
List<myEvent> mockEvents=new ArrayList<myEvent>();
myEvents.add(new MyEvent(......));
when(myService.executeRule(any(MyRule.class))).thenReturn(mockEvents);
String requestBody = ow.writeValueAsString(happyRule);
MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON)
.content(requestBody))
.andExpect(status().isOk())
.andExpect(
content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
verify(MyService,times(1)).executeRule(any(MyRule.class));
String jsonString = result.getResponse().getContentAsString();
}
}
Below is my controller class, where MyService is a interface. And I have implemented this interface.
#RestController
#RequestMapping("/api/rule")
public class MyController {
#Autowired
private MyService myService;
#RequestMapping(method = RequestMethod.POST,consumes = "application/json",produces = "application/json")
public List<MyEvent> eventsForRule(#RequestBody MyRule myRule) {
return myService.executeRule(myRule);
}
}
Is api your context root of the application? If so remove the context root from the request URI and test. Passing the context root will throw a 404. If you intend to pass the context root then please refer the below test case. Hope this helps.
#RunWith(MockitoJUnitRunner.class)
public class MyControllerTest {
#InjectMocks
private MyController myRulesController;
private MockMvc mockMvc;
#Before
public void setup() {
this.mockMvc = standaloneSetup(myRulesController).build();
}
#Test
public void controllerTest() throws Exception{
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
MyController.User user = new MyController.User("test-user");
ow.writeValueAsString(user);
MvcResult result = mockMvc.perform(post("/api/rule").contentType(MediaType.APPLICATION_JSON).contextPath("/api")
.content(ow.writeValueAsString(user)))
.andExpect(status().isOk())
.andExpect(
content().contentType(MediaType.APPLICATION_JSON))
.andReturn();
}
}
Below is the controller
/**
* Created by schinta6 on 4/26/16.
*/
#RestController
#RequestMapping("/api/rule")
public class MyController {
#RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
public User eventsForRule(#RequestBody User payload) {
return new User("Test-user");
}
public static class User {
private String name;
public User(String name){
this.name = name;
}
}
}

Categories

Resources