问:
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

```<code>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
</code>```

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

```<code>@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);
    }
}
</code>```

** my controller test class and the find method:

```<code>@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());
    }
}
</code>```

** my Email model

```<code>@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
}
</code>```

** 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
```

<p>** The JUnit fail log:</p>

```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

答:
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

```<code>@Sql({ "import.sql" })
</code>```

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

```<code>when(emailService.buscar(anyInt()).thenReturn(new Email());
</code>```

Body:
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

Body:
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());


来源: stackexchange

问:
Google Guice vs. JSR-299 CDI / Weld
Weld, the JSR-299 Contexts and Dependency Injection reference implementation, considers itself as a kind of successor of Spring and Guice.

CDI was influenced by a number of existing Java frameworks, including Seam, Guice and Spring. However, CDI has its own, very distinct, character: more typesafe than Seam, more stateful and less XML-centric than Spring, more web and enterprise-application capable than Guice. But it couldn't have been any of these without inspiration from the frameworks mentioned and lots of collaboration and hard work by the JSR-299 Expert Group (EG).

http://docs.jboss.org/weld/reference/latest/en-US/html/1.html

What makes Weld more capable for enterprise application compared to Guice? Are there any advantages or disadvantages compared to Guice? What do you think about Guice AOP compared to Weld interceptors? What about performance?

My choice

In the end I decided to use Guice because I like the clean programming model which comes almost without annotations besides @Inject by default. It is much easier to use external libs with Guice than with CDI. AOP is also pretty simple with Guice.

答:
The most important feature CDI has opposed to Guice, is that it is a standard part of Java EE 6.

The importance of this cannot be underestimated, as it means that CDI is the DI-standard you should use when coding web applications.

A while back I had a look at the technologies to be able to determine how we could have a standard core distribution - suitably prepared - where we could add extra modules at will which could override existing functionality without having to change the core modules.  I.e. add an extra jar, and the functionality activates automatically.

It turned out that the best way for us to do this for a code base used in both desktop and web applications, was to use JSR-330 annotations for our code, and then use either CDI or  Guice (SVN, coming real soon now in 3.0) as the engine.

After a few projects I've found that I like the Guice configuration best instead of the opaque magic happening in Weld.  Additionally I found that the way to do what we want as described above with Weld, I have to mark the class in the extra jar as @Alternative, and then mention in beans.xml that I want the alternative class enforced (and that is not robust against refactoring).

But, all in all,  JSR-330 allows us to do something which was very tedious and fragile before (because new binds so extremely tightly), and that is a great win.  I can strongly recommend looking into DI if you have any need like this.

ContentLicense: CC BY-SA 3.0

Title: Google Guice vs. JSR-299 CDI / Weld

ContentLicense: CC BY-SA 2.5


问:
Parse User log out does not work
I am using Parse 1.9.0 for Android and I need to log out user on button click, so I call:

```<code>ParseUser.logOut();
</code>```

After that I need to open login screen and click on Facebook login button, and to check if user have saved custom custom field.

But, it seems that ParseUser.getCurrentUser() after log out is not null.

How I can remove current user from cache?

答:
The logout() method is called from the current user object itself and to obtain it you call ParseUser.getCurrentUser() and then logout like below:

```<code>ParseUser.getCurrentUser().logOut();
</code>```

now the current user is null.
if ParseUser.enableAutomaticUser(); isn't called anywhere the current user will only be logged in using :

```<code>ParseUser.logInInBackground(username, password);
ParseUser parseUser = /*your user data here*/;
parseUser.signUpInBackground();
</code>```

Title: Parse User log out does not work

Body:
I am using Parse 1.9.0 for Android and I need to log out user on button click, so I call:

ParseUser.logOut();

After that I need to open login screen and click on Facebook login button, and to check if user have saved custom custom field.

But, it seems that ParseUser.getCurrentUser() after log out is not null.

How I can remove current user from cache?

Body:
The logout() method is called from the current user object itself and to obtain it you call ParseUser.getCurrentUser() and then logout like below:

ParseUser.getCurrentUser().logOut();

now the current user is null.
if ParseUser.enableAutomaticUser(); isn't called anywhere the current user will only be logged in using :

ParseUser.logInInBackground(username, password);
ParseUser parseUser = /*your user data here*/;
parseUser.signUpInBackground();


问:
Add the where clause dynamically in Entity Framework
I have this sql statement

```<code>SELECT userID from users WHERE
(name='name1' AND username='username1') OR
(name='name2' AND username='username2') OR
(name='name3' AND username='username3') OR
..........
(name='nameN' AND username='usernameN')
</code>```

How can I implement this statement with entity framework using LINQ?

答:
I had to construct the predicate for the 'Where' clause dynamically based on User Interface selections. 'System.Dynamic.Linq' allows to predicates from strings.

```<code>foreach (var name in names)
{
    query = query.Where("Name=@0 And UserName=@1", name, name);
}
return query;
</code>```

'System.Dynamic.Linq' is available as a nuget package. Check out Scott Guthrie's introduction to the topic here.

ContentLicense: CC BY-SA 4.0

Body:
I have this sql statement

SELECT userID from users WHERE
(name='name1' AND username='username1') OR
(name='name2' AND username='username2') OR
(name='name3' AND username='username3') OR
..........
(name='nameN' AND username='usernameN')

How can I implement this statement with entity framework using LINQ?

Body:
I had to construct the predicate for the 'Where' clause dynamically based on User Interface selections. 'System.Dynamic.Linq' allows to predicates from strings.

foreach (var name in names)
{
    query = query.Where("Name=@0 And UserName=@1", name, name);
}
return query;

'System.Dynamic.Linq' is available as a nuget package. Check out Scott Guthrie's introduction to the topic here.


问:
Autocomplete adding extra spaces
Image Example

Image Example Keyboard

My auto commplete is adding extra spaces when data is selected from web services, how do i fix this?
i've tried mostly everything but isnt getting any results

Code:

https://jsfiddle.net/jz1e4tr6/1/

```<code>$(document).ready(function () {
             $("#<%=TextBox1.ClientID%>").autocomplete({
                 source: function (request, response) {
                     $.ajax({
                         url: '<%=ResolveUrl("/Normal/WebServices/AutoComplete.asmx/GetSubject")%>',
                         data: "{ 'prefix': '" + request.term + "'}",
                         dataType: "json",
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         success: function (data) {
                             response($.map(data.d, function (item) {
                                 return {
                                     label: item.split('-')[0],
                                     attr: item.split('-')[1]
                                 }
                             }))
                         },
                         error: function (response) {
                             alert(response.responseText);
                         },
                         failure: function (response) {
                             alert(response.responseText);
                         }
                     });
                 },
</code>```

答: An alternative "tweak" but not the right solution... before clicking submit in the code behind... i get the value from the textbox and into a variable. And trim the variable.</p>

Title: Autocomplete adding extra spaces

Body:
Image Example

Image Example Keyboard

My auto commplete is adding extra spaces when data is selected from web services, how do i fix this?
i've tried mostly everything but isnt getting any results

Code:

https://jsfiddle.net/jz1e4tr6/1/

$(document).ready(function () {
             $("#<%=TextBox1.ClientID%>").autocomplete({
                 source: function (request, response) {
                     $.ajax({
                         url: '<%=ResolveUrl("/Normal/WebServices/AutoComplete.asmx/GetSubject")%>',
                         data: "{ 'prefix': '" + request.term + "'}",
                         dataType: "json",
                         type: "POST",
                         contentType: "application/json; charset=utf-8",
                         success: function (data) {
                             response($.map(data.d, function (item) {
                                 return {
                                     label: item.split('-')[0],
                                     attr: item.split('-')[1]
                                 }
                             }))
                         },
                         error: function (response) {
                             alert(response.responseText);
                         },
                         failure: function (response) {
                             alert(response.responseText);
                         }
                     });
                 },


问:
App Service Editor in Azure
The App Service Editor (Preview) in Azure

When I 'Initialize Git Repository', where is my git repository created? Is there a repository URL that I can use?

And if later, after finish changing my code, I want to export repository (e.g., get a copy to my local machine), how can I do that?

答:
You can access the git repository through command line or via the URL given in your instance dashboard in properties

there should be a Git URL field there.

Title: App Service Editor in Azure


问:
Why i can not change text view value in fragment?
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

```<code><TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</code>```

In fragment I wrote this simple method:

```<code>public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }
</code>```

I call that method in activity:

```<code>Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();
</code>```

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code

答: Clear your setTest() method in onCreate() and move it to  onCreateView().

Body:
I'm new to android, I wrote a simple app to learn fragments. I created a text view:

<TextView
        android:id="@+id/behzad"
        android:text="behzad"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

In fragment I wrote this simple method:

public void setTest(){

        TextView text=(TextView) FiveView.findViewById(R.id.behzad);
        text.setText("hahaha");
        Toast.makeText(getActivity().getBaseContext(), "ok", Toast.LENGTH_SHORT).show();
    }

I call that method in activity:

Fragment frag=adapter.getItem(4);
        ((FiveFragment)frag).setTest();

I get the ok message from toast but the fragment's text view does not show hahaha

Why the text view's value has not changed? This is my code


问:
Entity Framework - Virtual Property
I'm using Entity Framework with EDMX. I have a question about virtual property and how to use it. Let's begin by saying I've three tables in my database :

Inscriptions.idEvent is a FK of Events.id and Enfants.idInscription is a FK of Inscriptions.id.

This is the Inscriptions model generated :

```<code>public partial class Inscriptions
{
    public int id { get; set; }
    public int idEvent { get; set; }
    public string acronyme { get; set; }
    public string nom { get; set; }
    public string prenom { get; set; }
    public string bu { get; set; }
    public byte clubsocial { get; set; }
    public double montant { get; set; }

    public virtual Enfants Enfants { get; set; }
    public virtual Events Events { get; set; }
}
</code>```

Let assume that I want to add an Enfants to Inscriptions. How am I supposed to do that ? I thought it would be an ICollection, but since it's not that, I don't know what is a virtual property and how I add object to it.

Thanks !

答:
Thanks to @George Vovos and @Ivan Stoev.

I have updated my FK in SQL Server to set the relation one to many.

Title: Entity Framework - Virtual Property

Body:
I'm using Entity Framework with EDMX. I have a question about virtual property and how to use it. Let's begin by saying I've three tables in my database :

Inscriptions.idEvent is a FK of Events.id and Enfants.idInscription is a FK of Inscriptions.id.

This is the Inscriptions model generated :

public partial class Inscriptions
{
    public int id { get; set; }
    public int idEvent { get; set; }
    public string acronyme { get; set; }
    public string nom { get; set; }
    public string prenom { get; set; }
    public string bu { get; set; }
    public byte clubsocial { get; set; }
    public double montant { get; set; }

    public virtual Enfants Enfants { get; set; }
    public virtual Events Events { get; set; }
}

Let assume that I want to add an Enfants to Inscriptions. How am I supposed to do that ? I thought it would be an ICollection, but since it's not that, I don't know what is a virtual property and how I add object to it.

Thanks !


问:
How to limit table search to specific rows that contain specific text in a column
I am searching in my table with a function:

```<code>//search field for table
$("#search_field").keyup(function() {
var value = this.value;

$("#menu_table").find("tr").each(function(index) {
    if (index === 0) return;
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);

});});
</code>```

Fourth coulmn of data is Type i.e. Chicken, Kebabs etc.
I want to search only in those rows whose 4th column contains ('Chicken'). It should not search in rows whose Type is 'Kebabs'. The code above is searching in all rows.

答:
You can filter the rows and apply your code only to the filtered row like in:

```<code>$('#menu_table tr:gt(0)').filter(function(idx, ele) {
            return $(ele).find('td:eq(3)').text() == 'Chicken';
}).each(function(index, ele) {
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);
});
</code>```

Another way to filter is based on :nth-child() Selector:

```<code>$('#menu_table tr:gt(0) td:nth-child(4)').filter(function(idx, ele) {
    return ele.textContent == 'Chicken';
}).closest('tr').each(function(index, ele) {
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);
});
</code>```

$('#menu_table tr:gt(0) td:nth-child(4)').filter(function(idx, ele) {
    return ele.textContent == 'Chicken';
}).closest('tr').each(function(index, ele) {
    var id = $(this).find("td:first").text();
    var typ = $(this).find("td:eq(3)").text();
    console.log('ID:' + id + ' Type: ' + typ);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="menu_table">
    <thead>
    <tr>
        <th class="centerText" data-field="item_id">ID</th>
        <th class="centerText" data-field="name">Name</th>
        <th class="centerText" data-field="price">Price</th>
        <th class="centerText" data-field="type">Type</th>
        <th class="centerText" data-field="image">Image</th>
        <th class="centerText" data-field="description">Description</th>
        <th class="centerText" data-field="cooking">Instructions</th>
        <th class="centerText" data-field="ingredients">Ingredients</th>
        <th class="centerText" data-field="warnings">Warnings</th>
        <th class="centerText" data-field="Storage">Storage</th>
        <th class="centerText" data-field="Size">Size</th>
        <th class="centerText" data-field="edit">Edit</th>
        <th class="centerText" data-field="delete">Delete</th>
    </tr>
    </thead>
    <tbody style="text-align:center;" id="menu_table_data">
    <tr>
        <td>1</td>
        <td>name</td>
        <td>price</td>
        <td>type</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>2</td>
        <td>name</td>
        <td>price</td>
        <td>type</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>3</td>
        <td>name</td>
        <td>price</td>
        <td>not Chicken</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>4</td>
        <td>name</td>
        <td>price</td>
        <td>Chicken</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    </tbody>
</table></code>```

Body:
I am searching in my table with a function:

//search field for table
$("#search_field").keyup(function() {
var value = this.value;

$("#menu_table").find("tr").each(function(index) {
    if (index === 0) return;
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);

});});

Fourth coulmn of data is Type i.e. Chicken, Kebabs etc.
I want to search only in those rows whose 4th column contains ('Chicken'). It should not search in rows whose Type is 'Kebabs'. The code above is searching in all rows.

Body:
You can filter the rows and apply your code only to the filtered row like in:

$('#menu_table tr:gt(0)').filter(function(idx, ele) {
            return $(ele).find('td:eq(3)').text() == 'Chicken';
}).each(function(index, ele) {
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);
});

Another way to filter is based on :nth-child() Selector:

$('#menu_table tr:gt(0) td:nth-child(4)').filter(function(idx, ele) {
    return ele.textContent == 'Chicken';
}).closest('tr').each(function(index, ele) {
    var id = $(this).find("td").text();
    $(this).toggle(id.indexOf(value) !== -1);
});

$('#menu_table tr:gt(0) td:nth-child(4)').filter(function(idx, ele) {
    return ele.textContent == 'Chicken';
}).closest('tr').each(function(index, ele) {
    var id = $(this).find("td:first").text();
    var typ = $(this).find("td:eq(3)").text();
    console.log('ID:' + id + ' Type: ' + typ);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table id="menu_table">
    <thead>
    <tr>
        <th class="centerText" data-field="item_id">ID</th>
        <th class="centerText" data-field="name">Name</th>
        <th class="centerText" data-field="price">Price</th>
        <th class="centerText" data-field="type">Type</th>
        <th class="centerText" data-field="image">Image</th>
        <th class="centerText" data-field="description">Description</th>
        <th class="centerText" data-field="cooking">Instructions</th>
        <th class="centerText" data-field="ingredients">Ingredients</th>
        <th class="centerText" data-field="warnings">Warnings</th>
        <th class="centerText" data-field="Storage">Storage</th>
        <th class="centerText" data-field="Size">Size</th>
        <th class="centerText" data-field="edit">Edit</th>
        <th class="centerText" data-field="delete">Delete</th>
    </tr>
    </thead>
    <tbody style="text-align:center;" id="menu_table_data">
    <tr>
        <td>1</td>
        <td>name</td>
        <td>price</td>
        <td>type</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>2</td>
        <td>name</td>
        <td>price</td>
        <td>type</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>3</td>
        <td>name</td>
        <td>price</td>
        <td>not Chicken</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    <tr>
        <td>4</td>
        <td>name</td>
        <td>price</td>
        <td>Chicken</td>
        <td>image</td>
        <td>description</td>
        <td>instruction</td>
        <td>ingredients</td>
        <td>warnings</td>
        <td>storage</td>
        <td>size</td>
        <td>edit</td>
        <td>delete</td>
    </tr>
    </tbody>
</table>


问:
Is it possible to get authorized on twitter and change twitter status without asking users to enter PIN?
Is it possible to get authorized on twitter and change twitter status without asking users to enter PIN ? Or can i store access token to use it when user starts application next time ?</p>

答: You can also activate xAuth authentification. In order to do that you have to create your twitter app and ask xAuth activation to Twitter.</p>


问:
laravel ajax request params yields null
I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.

front end:

```<code>var taskdata= {
    "name": $("#new_task").val()
};

//console.log(JSON.stringify(taskdata));

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    processData: false,
    success: function(result) {
        alert("success");
    }
});
</code>```

server side:

```<code>Route::post('/task', function (Request $request) {

    //die(var_dump($request->json("name")));

    $validator = Validator::make(json_decode($request->getContent(), true), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return redirect('/');
});
</code>```

答:
Here's a better way to solve that:

```<code>Route::post('/task', function (Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);
    if ($validator->fails()) {
          throw new ValidationException($validator); //Your error handler should send JSON or redirect as appropriate.
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    if ($request->expectsJson()) {
        return response()->json(true); //Success
    } else {
        return redirect()->to("/");
    }
});
</code>```

Update:

You also need to let jQuery process the data so it constructs a proper query:

```<code>var taskdata= {"name": $("#new_task").val()};
        //console.log(JSON.stringify(taskdata));
        $.ajax({
            url: '/task',
            type: 'POST',
            data: taskdata,
            contentType: 'json',
            processData: true, //Or remove it completely since the default is true
            success: function(result) {
                alert("success");
            }
        });
</code>```

Title: laravel ajax request params yields null

Body:
I am new to laravel framework and started following the laravel tasks tutorial.
I am trying to pass via ajax request the name of the task in order to save it in the database.

front end:

var taskdata= {
    "name": $("#new_task").val()
};

//console.log(JSON.stringify(taskdata));

$.ajax({
    url: '/task',
    type: 'POST',
    data: taskdata,
    contentType: 'json',
    processData: false,
    success: function(result) {
        alert("success");
    }
});

server side:

Route::post('/task', function (Request $request) {

    //die(var_dump($request->json("name")));

    $validator = Validator::make(json_decode($request->getContent(), true), [
        'name' => 'required|max:255',
    ]);

    if ($validator->fails()) {
        return redirect('/')
            ->withInput()
            ->withErrors($validator);
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    return redirect('/');
});

Body:
Here's a better way to solve that:

Route::post('/task', function (Request $request) {
    $validator = Validator::make($request->all(), [
        'name' => 'required|max:255',
    ]);
    if ($validator->fails()) {
          throw new ValidationException($validator); //Your error handler should send JSON or redirect as appropriate.
    }

    $task = new \App\Task;
    $task->name = $request->name;
    $task->save();

    if ($request->expectsJson()) {
        return response()->json(true); //Success
    } else {
        return redirect()->to("/");
    }
});

Update:

You also need to let jQuery process the data so it constructs a proper query:

var taskdata= {"name": $("#new_task").val()};
        //console.log(JSON.stringify(taskdata));
        $.ajax({
            url: '/task',
            type: 'POST',
            data: taskdata,
            contentType: 'json',
            processData: true, //Or remove it completely since the default is true
            success: function(result) {
                alert("success");
            }
        });


问:
Iterate over all documents in solr
I have a solr instance with 200M+ documents. I would like to find an efficient way to iterate over all those documents.

I tried using the start parameter to formulate a list of queries:

```<code>http://ip:port/solr/docs/select?q=*:*&start=0&rows=1000000&fl=content&wt=python

http://ip:port/solr/docs/select?q=*:*&start=1000000&rows=1000000&fl=content&wt=python

...
</code>```

But it is very slow when start gets too high.

I also tried using the cursorMark parameter with an initial query like this one:

```<code>http://ip:port/solr/docs/select?q=*:*&cursorMark=*&sort=id+asc&start=0&rows=1000000&fl=content&wt=python
</code>```

which I believe try to sort all the documents first and crash the server. Sadly I don't think it is possible to bypass the sort. What would be the proper way to do it?

答:
this is a very well known antipattern. You just need to use cursorMark feature to go deep into a result set.

if  cursorMark is not doable then try the export handler

Title: Iterate over all documents in solr

Body:
I have a solr instance with 200M+ documents. I would like to find an efficient way to iterate over all those documents.

I tried using the start parameter to formulate a list of queries:

http://ip:port/solr/docs/select?q=*:*&start=0&rows=1000000&fl=content&wt=python

http://ip:port/solr/docs/select?q=*:*&start=1000000&rows=1000000&fl=content&wt=python

...

But it is very slow when start gets too high.

I also tried using the cursorMark parameter with an initial query like this one:

http://ip:port/solr/docs/select?q=*:*&cursorMark=*&sort=id+asc&start=0&rows=1000000&fl=content&wt=python

which I believe try to sort all the documents first and crash the server. Sadly I don't think it is possible to bypass the sort. What would be the proper way to do it?


问:
Why is curl using HTTP/1.1 rather than HTTP/2 on mac?
According to this https://curl.haxx.se/docs/http2.html

Since 7.47.0, the curl tool enables HTTP/2 by default for HTTPS connections.

Installing the latest version with homebrew and checking:

```<code>curl --version
curl 7.54.1 (x86_64-apple-darwin15.6.0) libcurl/7.54.1 SecureTransport zlib/1.2.5
</code>```

but running curl on an HTTP2 enabled URL (e.g. test with https://tools.keycdn.com/http2-test) I get:

```<code>curl -I http://www.google.co.uk
HTTP/1.1 200 OK
</code>```

and

```<code>curl --http2 -v http://www.google.co.uk
curl: (1) Unsupported protocol
</code>```

Any idea why it's using HTTP/1.1 rather than HTTP/2?

答:
With MacOS Sierra, this is how you can install an updated curl that supports HTTP2 by using OpenSSL instead of SecureTransport.

brew reinstall curl --with-openssl --with-nghttp2

brew link curl --force

Relaunch Terminal

curl -V should return something like this:

curl 7.54.1 (x86_64-apple-darwin16.6.0) libcurl/7.54.1 OpenSSL/1.0.2l
  zlib/1.2.8 nghttp2/1.24.0 Release-Date: 2017-06-14 Protocols: dict
  file ftp ftps gopher http https imap imaps ldap ldaps  pop3 pop3s rtsp
  smb smbs smtp smtps telnet tftp Features: IPv6 Largefile NTLM NTLM_WB
  SSL libz TLS-SRP HTTP2  UnixSockets HTTPS-proxy

I should note that MacOS minor point updates sometimes overwrite the curl version being used. If that happens, simply re-run brew link curl --force and relaunch terminal to switch back to the homebrew HTTP2 enabled version.

Body:
According to this https://curl.haxx.se/docs/http2.html

Since 7.47.0, the curl tool enables HTTP/2 by default for HTTPS connections.

Installing the latest version with homebrew and checking:

curl --version
curl 7.54.1 (x86_64-apple-darwin15.6.0) libcurl/7.54.1 SecureTransport zlib/1.2.5

but running curl on an HTTP2 enabled URL (e.g. test with https://tools.keycdn.com/http2-test) I get:

curl -I http://www.google.co.uk
HTTP/1.1 200 OK

and

curl --http2 -v http://www.google.co.uk
curl: (1) Unsupported protocol

Any idea why it's using HTTP/1.1 rather than HTTP/2?


问:
App re-install required for push notifications on iOS
I have some really weird behavior on iOS.
I have an app that used to use parse push notifications.
Since parse shut down on Jan 30th, I switched to back4app.
I was testing sending push notifications - my app was subscribed to a test channel and I was sending pushes to the channel.
I was using two phones.

At around 5pm, I was getting notifications correctly on both phones (phone1 running version A and phone2 running version B).
At around 6pm, I got notifications on only one phone (version B) and not the other (version A).
I logged into the phone, checked the app store, and updated version A -> B. So now both phones have version B.

Still phone1 had no notifications but phone2 did.
I then uninstalled the app on phone2 and reinstalled.
Now, at around 8pm, both phones get notifications.

It is really concerning that notifications stopped showing up on phone 1 and didn't show up even after the upgrade, and required re-install to work.
I register registerForRemoteNotifications in a plugin init call, and I confirmed from the logs that I successfully registered, and saved the token and was on the right channel.

Feb 13 19:23:30 ucb-sdb-iphone-1 emission[674] <Warning>: Successfully registered remote push notifications for token <c2a21dac d3e1678c 8fcde265 4552c3f6 64e507b9 94b4e092 300165b3 bfc747fe> with parse

The back4app dashboard shows that the status of the notifications was green. But they were not delivered. I am worried that my users won't get notifications properly because they are not going to uninstall and reinstall...

答:
For what I can tell for Back4App's Push Notification for iOS, there are two things that are mainly needed: a valid Certificate and proper Device Tokens.

On your case, since you haven't shared much of how different were your Version A and Version B I'm not really sure if any of those two key info were correct and working.

Also, the green status of the Push might not tell everything, since even if the Push is all set and the status is "SENT", the device might not receive it if it's installation code fails.

My suggestion would be to focus on those two key info, check their Documentation and give it a try at their Online Chat Support.


问:
How to round a time down to the nearest 15 minutes in Ruby?
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

```<code>t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)
</code>```

OwnerDisplayName: Readonly

Body:
Is there an easy way to round a Time down to the nearest 15 minutes?

This is what I'm currently doing.  Is there an easier way to do it?

t = Time.new
rounded_t = Time.local(t.year, t.month, t.day, t.hour, t.min/15*15)

Body:
You could do:

Time.at(t.to_i/(15*60)*(15*60))

OwnerDisplayName: Shalmanese


问:
http.responseText empty
I have a problem with my http.responseText (is always empty). I post my code:

```<code>function bCheckName ()
{
// It checks if the browser can allow a http request
if ( window.XMLHttpRequest )
{
    xhttp = new XMLHttpRequest();
}
else
{
    // for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// It takes the name from the form
var firstName = document.getElementById("firstName").value;
var datastring = "firstName=" + firstName;
var datastring_escaped = encodeURIComponent ( datastring );

// It opens the request to thye server
xhttp.open ( "POST", "../form/formValidation.php", true );

// It sets the header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// It sends the data to the server
xhttp.send( datastring_escaped );

// It takes the responde from the server
xhttp.onreadystatechange = function()
{
    if ( xhttp.readyState == 4 && xhttp.status == 200 )
    {

        var string      = xhttp.responseText.substr ( 0, 2 );
        var response    = xhttp.responseText.substr ( 5 );

        if ( string == "OK")
        {
            document.getElementById("nameResponse").innerHTML           = '<img src = "../img/pages/contact/true.png" alt = "correct answer" >';
            document.getElementById("response").innerHTML               = response;
        }
        else
        {
            document.getElementById("nameResponse").innerHTML           = '<img src = "../img/pages/contact/error.png" alt = "wrong answer">';
            document.getElementById("response").innerHTML               = response;
        }
    }
}

return false;}
</code>```

If I replace "xhttp.send( datastring_escaped );" with "xhttp.send( datastring );", everything will work as expected. How can I fix the problem. I post also the php code:

```<code>        if ( isset( $_POST['firstName'] ))
        {

        echo( "OK - ".urldecode ( $_POST['firstName']) );

        }
</code>```

How can I solve the problem?
Thanks in advance!!!

Francesco

答:
encodeURIComponent is only used for a part (component) of the URI.

```<code>encodeURIComponent("firstName=foobar")
</code>```

will give you "firstName%3Dfoobar". There will be no firstName request parameter and you can't read it from $_POST['firstName'].

If you really need to encode it, then only encode the firstName variable:

```<code>var datastring_escaped = "firstName=" + encodeURIComponent(firstName);
</code>```

Title: http.responseText empty

Body:
I have a problem with my http.responseText (is always empty). I post my code:

function bCheckName ()
{
// It checks if the browser can allow a http request
if ( window.XMLHttpRequest )
{
    xhttp = new XMLHttpRequest();
}
else
{
    // for IE6, IE5
    xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

// It takes the name from the form
var firstName = document.getElementById("firstName").value;
var datastring = "firstName=" + firstName;
var datastring_escaped = encodeURIComponent ( datastring );

// It opens the request to thye server
xhttp.open ( "POST", "../form/formValidation.php", true );

// It sets the header
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

// It sends the data to the server
xhttp.send( datastring_escaped );

// It takes the responde from the server
xhttp.onreadystatechange = function()
{
    if ( xhttp.readyState == 4 && xhttp.status == 200 )
    {

        var string      = xhttp.responseText.substr ( 0, 2 );
        var response    = xhttp.responseText.substr ( 5 );

        if ( string == "OK")
        {
            document.getElementById("nameResponse").innerHTML           = '';
            document.getElementById("response").innerHTML               = response;
        }
        else
        {
            document.getElementById("nameResponse").innerHTML           = '';
            document.getElementById("response").innerHTML               = response;
        }
    }
}

return false;}

If I replace "xhttp.send( datastring_escaped );" with "xhttp.send( datastring );", everything will work as expected. How can I fix the problem. I post also the php code:

        if ( isset( $_POST['firstName'] ))
        {

        echo( "OK - ".urldecode ( $_POST['firstName']) );

        }

How can I solve the problem?
Thanks in advance!!!

Francesco

Body:
encodeURIComponent is only used for a part (component) of the URI.

encodeURIComponent("firstName=foobar")

will give you "firstName%3Dfoobar". There will be no firstName request parameter and you can't read it from $_POST['firstName'].

If you really need to encode it, then only encode the firstName variable:

var datastring_escaped = "firstName=" + encodeURIComponent(firstName);


问:
What is file scope in javascript
What is variable declared within file scope in javascript?

Is there anything file scope, considering multiple files are used in an app.

答:
ES6 modules form their own file scope (as if the entire contents of the file were wrapped in a function).

Variables declared in a module are completely inaccessible from outside that module (unless they're exported).

Title: What is file scope in javascript


问:
Process Start Wont Work Cmd Window C#
I am working on a visual studio 2017 Project on C# and i tried to use the code Process Start. But when i tried it the command did not work cmd window opened but it did not write any command on the Window. What can i do ?</p>

```<code>private void button2_Click(object sender, EventArgs e)
{
    Process.Start("cmd", "command");
}
</code>```

答:
```<code>Process.Start("cmd", "/c command & pause");
</code>```

I added the & pause so you can see the window stay up.

If you don't want the window to show at all.

```<code>ProcessStartInfo info = new ProcessStartInfo( "cmd", "/c command" );
info.CreateNoWindow = true;
info.UseShellExecute = false;
Process.Start( info );
</code>```

Title: Process Start Wont Work Cmd Window C#

Body:
I am working on a visual studio 2017 Project on C# and i tried to use the code Process Start. But when i tried it the command did not work cmd window opened but it did not write any command on the Window. What can i do ?

private void button2_Click(object sender, EventArgs e)
{
    Process.Start("cmd", "command");
}

Body:
Process.Start("cmd", "/c command & pause");

I added the & pause so you can see the window stay up.

If you don't want the window to show at all.

ProcessStartInfo info = new ProcessStartInfo( "cmd", "/c command" );
info.CreateNoWindow = true;
info.UseShellExecute = false;
Process.Start( info );