Issue
I am setting up the unit testing on my @RestController's, but It is not working correctly.
This is only a unit test to validate the answer from the method of the RestEndpoint, but It is not working, please help me because I tried a lot of configurations and read the documentation and nothing worked.
This is my endpoint:
@RestController
@RequestMapping("/clients")
public class ClientsEndpoint extends RestConfiguration {
@Autowired
private IClientService clientService;
@GetMapping(value = "/{id}")
private Object getById(@PathVariable(required = true) Long id) {
try {
Optional<Client> clientOptional = clientService.getById(id);
if (clientOptional.isPresent()) {
return clientOptional.get();
} else
return new GeneralResponse(ErrorsEnum.CLIENT_NOT_FOUND);
} catch (Exception e) {
log.log(Level.SEVERE, "Problemas al obtener datos del cliente con id: " + id, e);
return new GeneralResponse(ErrorsEnum.GENERAL_ERROR);
}
}
This is my Unit Test where I only added the mock of the endpoint and a simple call is done:
@RunWith(SpringRunner.class)
@WebMvcTest(ClientsEndpoint.class)
@ContextConfiguration(classes={ApplicationConfiguration.class})
public class QuarzoApiApplicationTests {
@Autowired
private MockMvc mockMvc;
@MockBean
private IClientService clientService;
@Test
public void getById() throws Exception {
Client client = new Client("Test", "Test", "Test", (byte) 1,
"Test", "Test", "Test", "Test", (byte) 1,
(byte) 1, (short)1, "Test" );
Optional<Client> clientOptional = Optional.of(client);
BDDMockito.given(clientService.getById(anyLong())).willReturn(clientOptional);
this.mockMvc.perform(get("/clients/1")
.header("Authorization","Bearer " + TestUtils.createToken("miltonc")))
.andExpect(status().isOk());
}
Results I am getting after running the unit test:
2019-08-27 10:01:18.505 INFO 23606 --- [ main] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@7da39774, org.springframework.security.web.context.SecurityContextPersistenceFilter@5b7c8930, org.springframework.security.web.header.HeaderWriterFilter@4277127c, org.springframework.web.filter.CorsFilter@441b8382, org.springframework.security.web.authentication.logout.LogoutFilter@1a6dc589, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@40e32762, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@6f231ced, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@1df1ced0, org.springframework.security.web.session.SessionManagementFilter@2c05ff9d, org.springframework.security.web.access.ExceptionTranslationFilter@2a8a4e0c, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@27755487]
2019-08-27 10:01:18.526 INFO 23606 --- [ main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring TestDispatcherServlet ''
2019-08-27 10:01:18.527 INFO 23606 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Initializing Servlet ''
2019-08-27 10:01:18.533 INFO 23606 --- [ main] o.s.t.web.servlet.TestDispatcherServlet : Completed initialization in 6 ms
2019-08-27 10:01:18.555 INFO 23606 --- [ main] i.q.quarzoapi.QuarzoApiApplicationTests : Started QuarzoApiApplicationTests in 1.371 seconds (JVM running for 1.825)
MOCK org.springframework.test.web.servlet.MockMvc@770beef5
MockHttpServletRequest:
HTTP Method = GET
Request URI = /clients/1
Parameters = {}
Headers = [Authorization:"Bearer eyJhbGciOiJIUzUxMiJ9.eyJpYXQiOjE1NjY5MTQ0NzgsImlzcyI6IlFVQVJaTyIsInN1YiI6Im1pbHRvbmMiLCJleHAiOjE1NjY5NjQ4MDB9.hLu1Mcl_K-8smYnZnDu1ubkVTuNCkQnqhIQuypBsKBzQYxMlYlxqXhsYLCMB5iViCcDK33WXvO1Pjp15TR1ICg"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = org.springframework.web.servlet.resource.ResourceHttpRequestHandler
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 404
Error message = null
Headers = [X-Content-Type-Options:"nosniff", X-XSS-Protection:"1; mode=block", Cache-Control:"no-cache, no-store, max-age=0, must-revalidate", Pragma:"no-cache", Expires:"0", X-Frame-Options:"DENY"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Status
Expected :200
Actual :404
<Click to see difference>
at org.springframework.test.util.AssertionErrors.fail(AssertionErrors.java:55)
at org.springframework.test.util.AssertionErrors.assertEquals(AssertionErrors.java:82)
at org.springframework.test.web.servlet.result.StatusResultMatchers.lambda$matcher$9(StatusResultMatchers.java:619)
at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:195)
at io.quarzo.quarzoapi.QuarzoApiApplicationTests.getById(QuarzoApiApplicationTests.java:78)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
2019-08-27 10:01:18.772 INFO 23606 --- [ Thread-2] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'
Solution
I finally solved this. I needed to include the @ComponentScan(basePackages = "io.quarzo.api.endpoints") to refer the endpoints I am trying to test.
My Test configuration:
@Configuration
@ComponentScan(basePackages = "io.quarzo.api.endpoints")
public class ApplicationConfiguration extends WebSecurityConfigurerAdapter {
After that, I had to Mock every bean I was using in the endpoints.
@MockBean(name = "clientRegistrationSingleton")
private Map<String, Client> clientsRegistering;
@MockBean
private IClientService clientService;
@MockBean
private IClientRepository clientRepository;
After that all was working ok, I can run the test and mock every Bean to test my @RestController's.
Answered By - Milton BO