Search code examples
javaunit-testingspring-bootjunitspring-test-mvc

H2 in memory is empty when I run my unitary tests but it´s populated when I run the application itself


I am somewhat new to Spring Boot and for learning purposes, I wrote a simple REST API using an in-memory database (H2).

Everything works fine when I actually run the application: the database is loaded into memory and populated using an import.sql file I provided, my endpoints do what they are supposed to do. Now I´m trying to write a controller test that is supposed to call a "find stuff by id" endpoint. Here lies the problem: when I run this test, it doesn't find any entry in the database and fails, i.e., it seems my database has not been populated on startup. I don´t know what´s happening because, as I said, when I actually run the application and test it using Postman, everything is on memory and works as intended.

What should I do in order to get my database properly populated in a testing scenario?

Just for reference, I´ve read this article (very useful btw) and there, although he uses an alternative approach to populate his database, he doesn't do anything special regarding his testing needs. Everything runs fine both using Postman and when testing. This is what I try to accomplish.

Any help would be truly appreciated. I´ve done a lot of research, tried a lot of things, but to no avail.

These are the files I assume are relevant:

** my application.properties under /scr/main/resources

server.port=8888
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop

** my controller class and the find method I want to test.

@RestController
@RequestMapping(value="/email", produces=APPLICATION_JSON_VALUE)
public class EmailController {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EmailService emailService;

    @GetMapping(value="/{id}")
    public ResponseEntity<Email> consultar(@PathVariable Long id) {
        Email emailEncontrado = emailService.buscar(id);
        if (emailEncontrado == null) {
            LOGGER.info("No email has been found with this id... :(");
            return new ResponseEntity<Email>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<Email>(emailService.buscar(id), HttpStatus.OK);
    }
}

** my controller test class and the find method:

@RunWith(SpringRunner.class)
//@WebMvcTest(EmailController.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EmailControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private EmailService service;

    @Test
    public void deveBuscarEmailPorIdComSucesso() throws Exception {
        mvc.perform(get("/email/1"))
        .andExpect(jsonPath("$.id").value(1))
        .andDo(print());
    }
}

** my Email model

@Entity
@Table(name="t_email")
public class Email {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    private String emailTo;

    @Column(length=12000)
    private String message;

    private String subject;

    ** constructors, getters and setters
}

** The Spring Boot initialization log when I actually run the test (note the line at 2017-07-05 09:11:48.354)

09:11:28.619 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.email.controller.EmailControllerTest]
09:11:28.660 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
09:11:28.786 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
09:11:29.089 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.email.controller.EmailControllerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
09:11:29.198 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.email.controller.EmailControllerTest], using SpringBootContextLoader
09:11:29.229 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.email.controller.EmailControllerTest]: class path resource [com/aws/email/controller/EmailControllerTest-context.xml] does not exist
09:11:29.229 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.email.controller.EmailControllerTest]: class path resource [com/aws/email/controller/EmailControllerTestContext.groovy] does not exist
09:11:29.229 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.email.controller.EmailControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
09:11:29.229 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.email.controller.EmailControllerTest]: EmailControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
09:11:29.572 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.email.controller.EmailControllerTest]
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
09:11:29.697 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/aws/email/controller/] to resources [URL [file:/C:/Users/john.doe/workspace/project/bin/com/aws/email/controller/]]
09:11:29.710 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller]
09:11:29.710 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller] for files matching pattern [C:/Users/john.doe/workspace/project/bin/com/aws/email/controller/*.class]
09:11:29.712 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/aws/email/controller/*.class] to resources [file [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller\EmailController.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller\EmailControllerTest.class]]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/aws/email/] to resources [URL [file:/C:/Users/john.doe/workspace/project/bin/com/aws/email/]]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [C:\Users\john.doe\workspace\project\bin\com\aws\email]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [C:\Users\john.doe\workspace\project\bin\com\aws\email] for files matching pattern [C:/Users/john.doe/workspace/project/bin/com/aws/email/*.class]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/aws/email/*.class] to resources [file [C:\Users\john.doe\workspace\project\bin\com\aws\email\Application.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\ApplicationTests.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\GlobalExceptionHandler.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\TestBaseClass.class]]
09:11:30.009 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\Users\john.doe\workspace\project\bin\com\aws\email\Application.class]
09:11:30.025 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.email.Application for test class com.email.controller.EmailControllerTest
09:11:30.041 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.email.controller.EmailControllerTest]: using defaults.
09:11:30.041 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
09:11:30.169 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@40996815, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@17805bd5, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6c0d0900, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4bca166b, org.springframework.test.context.transaction.TransactionalTestExecutionListener@4085f1ac, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@19bd744c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@651e36c7, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@229e76ae, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5181ab43, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@1812e583, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@9a07ce, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7665b1]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.231 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@75152f9 testClass = EmailControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6c1e5d2f testClass = EmailControllerTest, locations = '{}', classes = '{class com.email.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@3d77f01d key = [Package Import com.email.controller, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@66edadfa, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@795eac8b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@72dbf050, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@169a567f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@e7e8512, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@67b3f915], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
09:11:30.231 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.231 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
09:11:30.525 [main] DEBUG org.springframework.core.env.MutablePropertySources - Adding [inline] PropertySource with highest search precedence
09:11:30.559 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
09:11:30.559 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [Inlined Test Properties] PropertySource with highest search precedence

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2017-07-05 09:11:31.932  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : Starting EmailControllerTest on INOTE79 with PID 11268 (started by john.doe in C:\Users\john.doe\workspace\project)
2017-07-05 09:11:31.932  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : No active profile set, falling back to default profiles: default
2017-07-05 09:11:33.355  INFO 11268 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:39.040  INFO 11268 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:39.104  INFO 11268 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-07-05 09:11:39.308  INFO 11268 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-07-05 09:11:39.308  INFO 11268 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-07-05 09:11:39.324  INFO 11268 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-07-05 09:11:39.443  INFO 11268 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-07-05 09:11:39.948  INFO 11268 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-07-05 09:11:40.073  INFO 11268 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2017-07-05 09:11:41.088  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-05 09:11:41.104  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000476: Executing import script '/import.sql'
2017-07-05 09:11:41.119  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-05 09:11:41.323  INFO 11268 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:44.571  INFO 11268 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2017-07-05 09:11:44.571  INFO 11268 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/email],methods=[POST],consumes=[application/json],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.email.response.EmailResponse> com.email.controller.EmailController.enviar(com.email.request.EmailRequest)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/email/{id}],methods=[GET],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.email.model.Email> com.email.controller.EmailController.consultar(java.lang.Long)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-05 09:11:45.119  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:45.119  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:45.228  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:46.370  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:46.556  INFO 11268 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in globalExceptionHandler
2017-07-05 09:11:46.823  INFO 11268 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 2252 ms
2017-07-05 09:11:47.948  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : Started EmailControllerTest in 17.313 seconds (JVM running for 21.805)
2017-07-05 09:11:48.354  INFO 11268 --- [           main] c.aws.email.controller.EmailController   : No email has been found with this id... :(

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /email/1
       Parameters = {}
          Headers = {}

Handler:
             Type = com.email.controller.EmailController
           Method = public org.springframework.http.ResponseEntity<com.email.model.Email> com.email.controller.EmailController.consultar(java.lang.Long)

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 = {}
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-05 09:11:48.432  INFO 11268 --- [       Thread-7] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete

** The JUnit fail log:

java.lang.AssertionError: No value at JSON path "$.id", exception: json can not be null or empty
    at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:245)
    at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:99)
    at org.springframework.test.web.servlet.result.JsonPathResultMatchers$2.match(JsonPathResultMatchers.java:100)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.email.controller.EmailControllerTest.deveBuscarEmailPorIdComSucesso(EmailControllerTest.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    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.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:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    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:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Edit: my project structure:

project tree


Solution

  • You need to define the dummy data before running the Unit test,the link you gave does that in the DemoApplication.class and loads it using @ContextConfiguration on the test class. That part is missing in your code.In your unit test the import.sql will not run until you mention it.It can be done using @Sql annotation

    @Sql({ "import.sql" })
    

    Also for unit test you dont need to make database calls,it is generally done in integration testing. For junits you can mock your service call as shown below

    when(emailService.buscar(anyInt()).thenReturn(new Email());