-1
Everything all right, guys? At the time I make a mock my error application and returns null of the mock, I have tried several ways to resolve, but it does not send anything different, could help me?
The test class still incomplete:
package br.com.globo.Infoglobo;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.BDDMockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;
import br.com.globo.Infoglobo.dto.NoticiaDto;
import br.com.globo.Infoglobo.dto.NoticiaResponseDto;
import br.com.globo.Infoglobo.model.Noticia;
import br.com.globo.Infoglobo.repository.NoticiaRepository;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class NoticiaIntegrationTest {
protected final String BASE_PATH = "http://localhost:";
@Autowired
private TestRestTemplate restTeamplate;
@LocalServerPort
private int port;
@MockBean
private NoticiaRepository noticiaRepository;
@Before
public void setUp() {
Optional<Noticia> noticia = Optional.of(new Noticia("123", "TITULO 1", "CONTEUDO 1", "20/02/2020"));
BDDMockito.when(noticiaRepository.findById(noticia.get().getId())).thenReturn(noticia);
}
@Test
public void findAllAndReturn200() {
Noticia noticia = new Noticia("ADS9DASD9", "TITULO 1", "CONTEUDO 1", "20/02/2020");
Noticia noticia2 = new Noticia("ADS9DASD8", "TITULO 2", "CONTEUDO 2", "20/02/2020");
List<Noticia> noticias = Arrays.asList(noticia, noticia2);
BDDMockito.when(noticiaRepository.findAll()).thenReturn(noticias);
ResponseEntity<String> response = restTeamplate.getForEntity("/noticia/", String.class);
Assert.assertEquals(200, response.getStatusCodeValue());
}
@Test
public void findByIdWhenIdExistsAndReturn200() {
ResponseEntity<String> response = restTeamplate.getForEntity("/noticia/123", String.class);
Assert.assertEquals(200, response.getStatusCodeValue());
}
@Test
public void findByIdWhenIdNotExistsAndReturn404() {
ResponseEntity<String> response = restTeamplate.getForEntity("/noticia/" + "-1", String.class);
Assert.assertEquals(404, response.getStatusCodeValue());
}
@Test
public void deleteWhenNoticiaExistsAndReturns200() {
BDDMockito.doNothing().when(noticiaRepository).deleteById("123");
ResponseEntity<String> response = restTeamplate.exchange("/noticia/{id}", HttpMethod.DELETE, null, String.class,
"123");
Assert.assertEquals(204, response.getStatusCodeValue());
}
@Test
public void deleteWhenNoticiaNotExistsAndReturns404() {
BDDMockito.doNothing().when(noticiaRepository).deleteById("-1");
ResponseEntity<String> response = restTeamplate.exchange("/noticia/{id}", HttpMethod.DELETE, null, String.class,
"-1");
Assert.assertEquals(404, response.getStatusCodeValue());
}
@Test
public void saveNoticiaAndReturns201() {
NoticiaDto noticiaDto = new NoticiaDto( "TITULO 1", "CONTEUDO 1");
Noticia noticia = new Noticia("1S34", "TITULO 1", "CONTEUDO 1", "20/02/2020");
BDDMockito.when(noticiaRepository.save(noticiaDto.transformaParaNoticia())).thenReturn(noticia);
ResponseEntity<NoticiaResponseDto> response = restTeamplate.postForEntity("/noticia/", noticiaDto, NoticiaResponseDto.class);
Assert.assertEquals(201, response.getStatusCodeValue());
}
@Test
public void createWhenTituloAndConteudoIsNullAndReturns400() {
}
}
The class Noticiadto
@Getter
@JsonIgnoreProperties(ignoreUnknown = true)
@NoArgsConstructor
public class NoticiaDto {
@NotNull
@NotEmpty
private String titulo;
@NotNull
@NotEmpty
private String conteudo;
private String dataPublicacao;
public Noticia transformaParaNoticia() {
return new Noticia(titulo, conteudo, dataPublicacao);
}
public Noticia transformaParaNoticiaSemDate() {
return new Noticia(titulo, conteudo);
}
public NoticiaDto(@NotNull @NotEmpty String titulo, @NotNull @NotEmpty String conteudo) {
this.titulo = titulo;
this.conteudo = conteudo;
}
}
The Class news
@Getter
@NoArgsConstructor
@Document(collection = "noticia")
public class Noticia {
@Id
private String id;
@NotEmpty
@NotNull
private String titulo;
@NotEmpty
@NotNull
private String conteudo;
private String dataPublicacao;
public Noticia(String titulo, String conteudo, String dataPublicacao) {
this.titulo = titulo;
this.conteudo = conteudo;
this.dataPublicacao = dataPublicacao == null? FormataData.retornaDataFormatadaLocal() : dataPublicacao;
}
public Noticia(String id, String titulo, String conteudo, String dataPublicacao) {
this.id = id;
this.titulo = titulo;
this.conteudo = conteudo;
this.dataPublicacao = dataPublicacao == null? FormataData.retornaDataFormatadaLocal() : dataPublicacao;
}
public Noticia(String titulo, String conteudo) {
this.titulo = titulo;
this.conteudo = conteudo;
this.dataPublicacao = FormataData.retornaDataFormatadaLocal();
}
}
This is the Log
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.3.2.RELEASE)
2020-08-04 01:09:47.564 INFO 12560 --- [ main] b.c.g.Infoglobo.NoticiaIntegrationTest : Starting NoticiaIntegrationTest on DESKTOP-CG3JEC5 with PID 12560 (started by Pedro in H:\Infoglobo workspace\Infoglobo)
2020-08-04 01:09:47.566 INFO 12560 --- [ main] b.c.g.Infoglobo.NoticiaIntegrationTest : No active profile set, falling back to default profiles: default
2020-08-04 01:09:48.608 INFO 12560 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data MongoDB repositories in DEFAULT mode.
2020-08-04 01:09:48.683 INFO 12560 --- [ main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 69ms. Found 1 MongoDB repository interfaces.
2020-08-04 01:09:49.916 INFO 12560 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 0 (http)
2020-08-04 01:09:49.935 INFO 12560 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-08-04 01:09:49.935 INFO 12560 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.37]
2020-08-04 01:09:50.056 INFO 12560 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-08-04 01:09:50.056 INFO 12560 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 2449 ms
2020-08-04 01:09:50.814 INFO 12560 --- [ main] pertySourcedRequestMappingHandlerMapping : Mapped URL path [/v2/api-docs] onto method [springfox.documentation.swagger2.web.Swagger2Controller#getDocumentation(String, HttpServletRequest)]
2020-08-04 01:09:51.099 INFO 12560 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-08-04 01:09:51.375 INFO 12560 --- [ main] org.mongodb.driver.cluster : Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms'}
2020-08-04 01:09:51.442 INFO 12560 --- [localhost:27017] org.mongodb.driver.connection : Opened connection [connectionId{localValue:1, serverValue:1095}] to localhost:27017
2020-08-04 01:09:51.447 INFO 12560 --- [localhost:27017] org.mongodb.driver.cluster : Monitor thread successfully connected to server with description ServerDescription{address=localhost:27017, type=STANDALONE, state=CONNECTED, ok=true, minWireVersion=0, maxWireVersion=8, maxDocumentSize=16777216, logicalSessionTimeoutMinutes=30, roundTripTimeNanos=3018400}
2020-08-04 01:09:51.820 INFO 12560 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 55709 (http) with context path ''
2020-08-04 01:09:51.821 INFO 12560 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Context refreshed
2020-08-04 01:09:51.838 INFO 12560 --- [ main] d.s.w.p.DocumentationPluginsBootstrapper : Found 1 custom documentation plugin(s)
2020-08-04 01:09:51.880 INFO 12560 --- [ main] s.d.s.w.s.ApiListingReferenceScanner : Scanning for api listing references
2020-08-04 01:09:51.900 INFO 12560 --- [ main] b.c.g.Infoglobo.NoticiaIntegrationTest : Started NoticiaIntegrationTest in 4.72 seconds (JVM running for 5.568)
2020-08-04 01:09:52.187 INFO 12560 --- [o-auto-1-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2020-08-04 01:09:52.188 INFO 12560 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2020-08-04 01:09:52.207 INFO 12560 --- [o-auto-1-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 19 ms
2020-08-04 01:09:52.374 ERROR 12560 --- [o-auto-1-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
java.lang.NullPointerException: null
at br.com.globo.Infoglobo.controller.NoticiaController.salvar(NoticiaController.java:120) ~[classes/:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:566) ~[na:na]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) ~[spring-webmvc-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) ~[tomcat-embed-core-9.0.37.jar:4.0.FR]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[tomcat-embed-websocket-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) ~[spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[na:na]
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[tomcat-embed-core-9.0.37.jar:9.0.37]
at java.base/java.lang.Thread.run(Thread.java:834) ~[na:na]
2020-08-04 01:09:52.690 INFO 12560 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor : Shutting down ExecutorService 'applicationTaskExecutor'