问:
Why doesn't my negative margin work in IE7?
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

```<code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

<style type="text/css">

.container {
 width: 800px;
 background: none;
 position:relative;
}
.container-mid{
 background:#F00;/**/
 border:dashed thick #090;
 width:100%;
}
.container-bottom{
 background:#FF0;/**/
 border:dashed thick #090;
 width:100%;
 height: 200px;
}
.container-inner{
 width:100%;
 margin:0 auto;
 margin-bottom:-200px;/**/

}

</style>

</head>

<body>

<div class="container">

    <div class="container-mid">

        <div class="container-inner">

            <div class="content">

                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>
                <br />
                <br />
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.</p>

            </div><!-- end .content -->

        </div><!-- end .container-inner -->

    </div><!-- end .container-mid -->

    <div class="container-bottom"></div>

  <!-- end .container --></div>

</body>
</html>
</code>```

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

答:
Another approach would be to only use a single div.  Set the background to be yellow, with a repeat-x background of red which is 200px high</p>

```<code>.container {
    background: url('red_back.png') repeat-x 0 0 yellow;
    }
</code>```

Body:
I have two stacked divs, where I want the content from the top div to flow over onto the bottom div.  Using a negative bottom margin on the content wrapper, I was able to achieve this in all browsers except IE 7, where instead of flowing over the bottom div, the content gets cut-off/overlapped by it.

I'm looking for an explanation of what exactly is happening here, and potential fixes.

Complete HTML example:

 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Negative Margin Test</title>

<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/3.2.0/build/cssreset/reset-min.css">

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sit amet bibendum tortor. Etiam at diam vitae mauris venenatis varius. Nam nec mauris ut ligula dictum fringilla a accumsan diam. Fusce ac mauris in lacus venenatis bibendum non eget nisl. In quis pretium dolor. In hac habitasse platea dictumst. Nam at quam et velit faucibus cursus. Aenean ut augue id augue suscipit condimentum sed eu est. Pellentesque commodo ipsum nec ligula aliquet a lobortis augue pharetra. Curabitur pretium luctus posuere. Proin id nisi sed lectus commodo porta. Fusce leo augue, lacinia eu tincidunt sed, faucibus at turpis. Aenean ut mi nulla. Duis orci urna, euismod quis mollis interdum, pharetra quis enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Morbi gravida eleifend ante ac hendrerit. Nunc ultricies tellus mauris.

In IE8: (Results same with Chrome/FFox/etc...)

In IE 7: (Tested with IE8->Developer Tools->IE7 Mode)

As you can see, overflowing content gets overlapped by the yellow div.

See my live example

Body:
Another approach would be to only use a single div.  Set the background to be yellow, with a repeat-x background of red which is 200px high

.container {
    background: url('red_back.png') repeat-x 0 0 yellow;
    }


来源: stackexchange

问:
how to override STL container function
It's possible, that override some function stl container with the same paremeters?
I want override exactly push_back with some if inside function.
I try but, always have error/information about that function is in vector.

答:
You cant do that. Most classes in the std library are not meant to be inherited from. However, instead of changing it "from the inside" just do it "from the outside", for example:

```<code>template<typename T> myPush(std::vector<T>& v,T element) {
    if (someCondition()) { v.push(element); }
}
</code>```

Alternatively, you could do this:

```<code>struct MyCustomVector {
     void my_push( T element);
     /* pulic or private: */          // depends on what you want/need
     std::vector<T> vect;
};
</code>```

ContentLicense: CC BY-SA 3.0

Title: how to override STL container function

Body:
You cant do that. Most classes in the std library are not meant to be inherited from. However, instead of changing it "from the inside" just do it "from the outside", for example:

template<typename T> myPush(std::vector<T>& v,T element) {
    if (someCondition()) { v.push(element); }
}

Alternatively, you could do this:

struct MyCustomVector {
     void my_push( T element);
     /* pulic or private: */          // depends on what you want/need
     std::vector<T> vect;
};


问:
How to read chunks for a text file based on a word as a key delimiter?
I have a .txt file with this format:

```<code>Part #368 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #369 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #370 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
</code>```

I read the file like this:

```<code>var lines = fs.readFileSync('file.txt', 'utf-8')
.split('\n')
.filter(Boolean);
</code>```

So it returns an array of the lines of the file. How can I get the chunks of the file starting with the "Part" string?

```<code>var parts = _.filter(lines,function( s ) { return s.indexOf( 'Part' ) !== -1; });
</code>```

Something like this but instead of getting the strings starting with "Part" I want all the lines from "Part" string to next "Part" string.

答:
This creates an array of array of lines.</p>

```<code>var parts = _.reduce(lines, function( result, line ) {
    if (line.indexOf('Part') !== -1) result.push([]);
    _.last(result).push(line);
    return result;
}, []);
</code>```

Body:
I have a .txt file with this format:

Part #368 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #369 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

Part #370 - XXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

I read the file like this:

var lines = fs.readFileSync('file.txt', 'utf-8')
.split('\n')
.filter(Boolean);

So it returns an array of the lines of the file. How can I get the chunks of the file starting with the "Part" string?

var parts = _.filter(lines,function( s ) { return s.indexOf( 'Part' ) !== -1; });

Something like this but instead of getting the strings starting with "Part" I want all the lines from "Part" string to next "Part" string.

Body:
This creates an array of array of lines.

var parts = _.reduce(lines, function( result, line ) {
    if (line.indexOf('Part') !== -1) result.push([]);
    _.last(result).push(line);
    return result;
}, []);


问:
how to break a function in java
guys i am a beginner in java ... i want to make a function to loop through a hashmap for example it contains

```<code>0[3],3[4,5],6[2]
</code>```

and to break when the method isSiteInherited is true else return false... here is what i made

```<code>  private boolean isInherited() {
  boolean isInherited = false;
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
      for (Integer index : entry.getValue()) {
          if(isSiteInherited(index)){
              break;
          }
      }
    }
    return false;
  }
</code>```

if not sites are found inherited return false and if it enters the break it should break from all the method ... so what is wrong with this method

答:
You can either use a label to break from the outer loop (https://stackoverflow.com/a/886979/4949918).

The better way would probably be to use a boolean to say that you've broken from the inner loop in the outer loop.

```<code>  private boolean isInherited() {
  boolean isInherited = false;
  boolean shouldBreak = false;
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
      for (Integer index : entry.getValue()) {
          if(isSiteInherited(index)){
              shouldBreak = true;
              break;
          }
      }
      if (shouldBreak) {
           break;
      }
    }
    return false;
  }
</code>```

Title: how to break a function in java

Body:
guys i am a beginner in java ... i want to make a function to loop through a hashmap for example it contains

0[3],3[4,5],6[2]

and to break when the method isSiteInherited is true else return false... here is what i made

  private boolean isInherited() {
  boolean isInherited = false;
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
      for (Integer index : entry.getValue()) {
          if(isSiteInherited(index)){
              break;
          }
      }
    }
    return false;
  }

if not sites are found inherited return false and if it enters the break it should break from all the method ... so what is wrong with this method

Body:
You can either use a label to break from the outer loop (https://stackoverflow.com/a/886979/4949918).

The better way would probably be to use a boolean to say that you've broken from the inner loop in the outer loop.

  private boolean isInherited() {
  boolean isInherited = false;
  boolean shouldBreak = false;
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
      for (Integer index : entry.getValue()) {
          if(isSiteInherited(index)){
              shouldBreak = true;
              break;
          }
      }
      if (shouldBreak) {
           break;
      }
    }
    return false;
  }


问:
Why does the original list change?
Running this:

```<code>a = [[1], [2]]
for i in a:
    i *= 2
print(a)
</code>```

Gives

```<code>[[1, 1], [2, 2]]
</code>```

I would expect to get the original list, as happens here:

```<code>a = [1, 2]
for i in a:
    i *= 2
print(a)
</code>```

Which gives:

```<code>[1, 2]
</code>```

Why is the list in the first example being modified?

答:
The reason your results are different for each example is because list are mutable, but integers are not.

That means when you you modify an integer object in place, the operator must return a new integer object. However, since list are mutable, the changes are simply added to already existing list object.

When you used *= in the for-loop in the first example, Python modify the already existing list. But when you used *= with the integers, a new integer object had to be returned.

This can also be observed with a simple example:

```<code>>>> a = 1
>>> b = [1]
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>
>>> a *= 1
>>> b *= 1
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>
</code>```

As you can see above, the memory address for a changed when we multiplied it in-place. So *= returned a new object. But the memory for the list did not change. That means *= modified the list object in-place.

Title: Why does the original list change?

Body:
Running this:

a = [[1], [2]]
for i in a:
    i *= 2
print(a)

Gives

[[1, 1], [2, 2]]

I would expect to get the original list, as happens here:

a = [1, 2]
for i in a:
    i *= 2
print(a)

Which gives:

[1, 2]

Why is the list in the first example being modified?

Body:
The reason your results are different for each example is because list are mutable, but integers are not.

That means when you you modify an integer object in place, the operator must return a new integer object. However, since list are mutable, the changes are simply added to already existing list object.

When you used *= in the for-loop in the first example, Python modify the already existing list. But when you used *= with the integers, a new integer object had to be returned.

This can also be observed with a simple example:

>>> a = 1
>>> b = [1]
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>
>>> a *= 1
>>> b *= 1
>>>
>>> id(a)
1505450256
>>> id(b)
52238656
>>>

As you can see above, the memory address for a changed when we multiplied it in-place. So *= returned a new object. But the memory for the list did not change. That means *= modified the list object in-place.


答:
Seems to be like you want to return instead of break.  Without the use of labels, break only gets you out of one layer of loops anyway, and in this case, you need to report overall success, which isn't something your current approach does.

```<code>private boolean isInherited() {
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
        for (Integer index : entry.getValue()) {
            if (isSiteInherited(index)) {
                return true;
            }
        }
    }
    return false;
}
</code>```

Title: how to break a function in java

Body:
Seems to be like you want to return instead of break.  Without the use of labels, break only gets you out of one layer of loops anyway, and in this case, you need to report overall success, which isn't something your current approach does.

private boolean isInherited() {
    for (Entry<Integer, Set<Integer>> entry : siteIndeciesMap.entrySet()) {
        for (Integer index : entry.getValue()) {
            if (isSiteInherited(index)) {
                return true;
            }
        }
    }
    return false;
}


问:
Convert object to array in php
I am converting object to array using

```<code>$data['payment_cheque'] = (array)$data['payment_cheque'];
</code>```

What i Get is

```<code>    "\u0000*\u0000items": ["2017-04-18","2017-06-28","2017-07-05"]
</code>```

What I want is

```<code>["2017-04-18","2017-06-28","2017-07-05"]
</code>```

答:
Just try this</p>

```<code>$data['payment_cheque'] =json_decode(json_encode($data['payment_cheque'] ,true),true);
</code>```

Title: Convert object to array in php

Body:
I am converting object to array using

$data['payment_cheque'] = (array)$data['payment_cheque'];

What i Get is

    "\u0000*\u0000items": ["2017-04-18","2017-06-28","2017-07-05"]

What I want is

["2017-04-18","2017-06-28","2017-07-05"]

Body:
Just try this

$data['payment_cheque'] =json_decode(json_encode($data['payment_cheque'] ,true),true);


问:
Difference between binding with map index or dot notation
Are there any functional or performance differences between the following two blocks?

```<code><foo ng-if="bar['qux']">
<foo ng-if="bar.qux">
</code>```

Does it make a difference if bar.qux is/isn't initially defined?

Note: I fully understand how objects work in plain Javascript. This is a NOT a question about Javascript, it's about differences that might exist in AngularJS (because of parsing, or any other implementation details)

答: With dot notation, after the initialization the object relationship never changes since the periodic calls.</p>

Body:
Are there any functional or performance differences between the following two blocks?

<foo ng-if="bar['qux']">
<foo ng-if="bar.qux">

Does it make a difference if bar.qux is/isn't initially defined?

Note: I fully understand how objects work in plain Javascript. This is a NOT a question about Javascript, it's about differences that might exist in AngularJS (because of parsing, or any other implementation details)


问:
Ordering module build order IntelliJ for maven projects
How can I set an order to the build of multiple projects (modules) in IntelliJ?</p>

答:
Open run edit configurations.

Create a new Maven Runner.

Add All you Modules to the "Before launch" tab selecting "Run another configuration"


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

答:
JUnit issue (which is basically assertion issue) which says there is no ID meaning two things:

Resulting JSON does not contain ID

Resulting JSON empty

your case is second, cause ID I can see from you Entity and also I see you have create-drop hibernate DDL, but note that it is not populating DB with dummy information and just creating that.

So, that will mean, that you need to populate DB with some dummy data.

For that, you can add a file named "import.sql" to your classpath (i.e. in src/main/resources if you're using a Maven/Gradle project layout).

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


问:
Login with Google OpenID or other providers
I am trying to figure out how OpenID works, therefore I am trying to write my own simple class for my web app that uses Google OpenID.

I am wondering if there are any examples that you know, or where I can find some details so I can implement my own class.

I am not looking for a very general class. I need something that will help me write my own implementation.

答:
I have made good experiences with lightopenid (gitorious download). Unlike two other OpenID libraries I tried for PHP, it was very easy to use, has no external dependencies, is compatible with PHP5 and has no warnings.

There is an example for using Google.

And to display those buttons in the HTML page: http://code.google.com/p/openid-selector/


问:
Phoenix started throwing (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private
After and update to my system - MAC, my phoenix app compile just fine but throw this error any time I hit any route.

Server: localhost:4000 (http) Request: GET /
  ** (exit) an exception was raised:
      ** (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private. Did you mean one of:

```<code>  * rand_seed/0
  * rand_seed/1

    (crypto) :crypto.rand_bytes(20)
    (plug) lib/plug/request_id.ex:59: Plug.RequestId.generate_request_id/0
    (plug) lib/plug/request_id.ex:48: Plug.RequestId.get_request_id/2
    (plug) lib/plug/request_id.ex:42: Plug.RequestId.call/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.phoenix_pipeline/1
    (olars) lib/plug/debugger.ex:93: Olars.Endpoint."call (overridable 3)"/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
</code>```

My mix.exs

```<code>{:phoenix, "~> 1.2.0"},
      {:phoenix_pubsub, "~> 1.0"},
      {:phoenix_ecto, "~> 3.0"},
      {:phoenix_haml, github: "chrismccord/phoenix_haml"},
      {:mariaex, ">= 0.0.0"},
      {:phoenix_html, "~> 2.6"},
      {:phoenix_live_reload, "~> 1.0", only: :dev},
      {:gettext, "~> 0.11"},
      {:cowboy, "~> 1.0"},
      {:arc,  "~> 0.5.2"},
      {:arc_ecto, "~> 0.3.2"},
      {:ex_aws, "~> 0.4.10"},
      {:httpoison, "~> 0.9"},
      {:poison, "~> 2.0"},
      {:ecto, "~> 2.0.2", override: true},
      {:plug_auth, github: "smpallen99/plug_auth"},
      {:comeonin, "~> 2.1.0"},
      {:phoenix_calendar, "~> 0.1.2"},
      {:httpotion, "~> 3.0.0", override: true},
      {:timex, "~> 3.0"},
      {:quantum,github: "c-rack/quantum-elixir"},
      {:calendar, "~> 0.16.1"},
      {:uri_query, "~> 0.1.1"},
      {:scrivener, "~> 2.0"},
      {:scrivener_list, "~> 1.0"},
      {:number, "~> 0.5.0"},
      {:xlsxir, "~> 1.4.1"},
      {:new_relic, "~> 0.1.1"},
      {:retry, "~> 0.7"},
      {:credo, "~> 0.8", only: [:dev, :test], runtime: false}
</code>```

Elixr version: Elixir 1.4.5
Erlang Version: 20

Let me know if you guys need any other info.

答:
:crypto.rand_bytes/1 was removed in OTP 20. You should use :crypto.strong_rand_bytes/1 instead.

In this case, it looks like you need to update plug to have this commit. You can run mix deps.update plug to do this.

Body:
After and update to my system - MAC, my phoenix app compile just fine but throw this error any time I hit any route.

Server: localhost:4000 (http) Request: GET /
  ** (exit) an exception was raised:
      ** (UndefinedFunctionError) function :crypto.rand_bytes/1 is undefined or private. Did you mean one of:

  * rand_seed/0
  * rand_seed/1

    (crypto) :crypto.rand_bytes(20)
    (plug) lib/plug/request_id.ex:59: Plug.RequestId.generate_request_id/0
    (plug) lib/plug/request_id.ex:48: Plug.RequestId.get_request_id/2
    (plug) lib/plug/request_id.ex:42: Plug.RequestId.call/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.phoenix_pipeline/1
    (olars) lib/plug/debugger.ex:93: Olars.Endpoint."call (overridable 3)"/2
    (olars) lib/olars/endpoint.ex:1: Olars.Endpoint.call/2
    (plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
    (cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4

My mix.exs

{:phoenix, "~> 1.2.0"},
      {:phoenix_pubsub, "~> 1.0"},
      {:phoenix_ecto, "~> 3.0"},
      {:phoenix_haml, github: "chrismccord/phoenix_haml"},
      {:mariaex, ">= 0.0.0"},
      {:phoenix_html, "~> 2.6"},
      {:phoenix_live_reload, "~> 1.0", only: :dev},
      {:gettext, "~> 0.11"},
      {:cowboy, "~> 1.0"},
      {:arc,  "~> 0.5.2"},
      {:arc_ecto, "~> 0.3.2"},
      {:ex_aws, "~> 0.4.10"},
      {:httpoison, "~> 0.9"},
      {:poison, "~> 2.0"},
      {:ecto, "~> 2.0.2", override: true},
      {:plug_auth, github: "smpallen99/plug_auth"},
      {:comeonin, "~> 2.1.0"},
      {:phoenix_calendar, "~> 0.1.2"},
      {:httpotion, "~> 3.0.0", override: true},
      {:timex, "~> 3.0"},
      {:quantum,github: "c-rack/quantum-elixir"},
      {:calendar, "~> 0.16.1"},
      {:uri_query, "~> 0.1.1"},
      {:scrivener, "~> 2.0"},
      {:scrivener_list, "~> 1.0"},
      {:number, "~> 0.5.0"},
      {:xlsxir, "~> 1.4.1"},
      {:new_relic, "~> 0.1.1"},
      {:retry, "~> 0.7"},
      {:credo, "~> 0.8", only: [:dev, :test], runtime: false}

Elixr version: Elixir 1.4.5
Erlang Version: 20

Let me know if you guys need any other info.


问:
ES6 - Yield and Return at the Same Time
I have this,

```<code>function*(a){
 if (a) {
    yield API.callRoute();
    return;
  }
  // other stuff that is blocked by return
}
</code>```

I want this:

```<code>function*(a){
  if (a) {
    return yield API.callRoute(); // one fewer line of code
  }
  //...
}
</code>```

Doable? Why? Why not?

答:
Yes, it's doable, but your second snippet returns the result of the yield expression. If you don't want that but make it exactly equivalent to your first snippet, use

```<code>return void yield API.callRoute();
</code>```

though probably it's not worth making this a line shorter when the difference is significant.

Title: ES6 - Yield and Return at the Same Time

Body:
I have this,

function*(a){
 if (a) {
    yield API.callRoute();
    return;
  }
  // other stuff that is blocked by return
}

I want this:

function*(a){
  if (a) {
    return yield API.callRoute(); // one fewer line of code
  }
  //...
}

Doable? Why? Why not?

Body:
Yes, it's doable, but your second snippet returns the result of the yield expression. If you don't want that but make it exactly equivalent to your first snippet, use

return void yield API.callRoute();

though probably it's not worth making this a line shorter when the difference is significant.


问:
Append d3.gantt chart to a selected div
I create a D3 Gantt chart.

with morte or less this code:

```<code>var gantt = d3.gantt().taskTypes(taskNames).taskStatus(taskStatus)
gantt(tasks)
</code>```

this automatically creates a new svg called chart.

I want to add it to my existing div

```<code><div id ="resultContainer">
</div>
</code>```

I did some research in thesource code over at github (https://github.com/dk8996/Gantt-Chart/blob/master/gantt-chart-d3.js quite in the end) and found the possibility to set a selector like

```<code>d3.gantt().taskTypes(taskNames).taskStatus(taskStatus).selector('#resultContainer')
</code>```

But that crashes.
Does anybody know how to add it to an existing div?

答:
Apparently, this is a mistake from the author of that library.

At the end of the code he wrote this:

```<code>gantt.selector = function(value) {
if (!arguments.length)
    return selector;
selector = value;
return gantt;
};
</code>```

Which, as you pointed out, could allow the user to set the selector.

However, at the beginning of the code, he wrote...

```<code>var selector = 'body';
</code>```

... which renders the previous function useless. It always appends to the .

Solution: Download the library and create your own version, changing...

```<code>var selector = 'body';
</code>```

... for just:

```<code>var selector;
</code>```

With that change you can pass your selection using selector().

Here is a demo, I'm using a bl.locks from the same author of the library. I copied the library and changed the mentioned variable. In the HTML, I created a div with a class .foo before a paragraph with a lorem ipsum. Then, I selected the div with:

```<code>var gantt = d3.gantt().selector(".foo").taskTypes(taskNames).etc...
</code>```

You can see (inspecting the page) that the chart is appended to the div, not to the body: http://bl.ocks.org/anonymous/raw/84385e7c6ac859ad24feb3662e46e3fd/

Actually, you don't even need to inspect the page: if it was appended to the body the lorem ipsum would be above the chart, not below, as it is.

Title: Append d3.gantt chart to a selected div

Body:
I create a D3 Gantt chart.

with morte or less this code:

var gantt = d3.gantt().taskTypes(taskNames).taskStatus(taskStatus)
gantt(tasks)

this automatically creates a new svg called chart.

I want to add it to my existing div

I did some research in thesource code over at github (https://github.com/dk8996/Gantt-Chart/blob/master/gantt-chart-d3.js quite in the end) and found the possibility to set a selector like

d3.gantt().taskTypes(taskNames).taskStatus(taskStatus).selector('#resultContainer')

But that crashes.
Does anybody know how to add it to an existing div?

Body:
Apparently, this is a mistake from the author of that library.

At the end of the code he wrote this:

gantt.selector = function(value) {
if (!arguments.length)
    return selector;
selector = value;
return gantt;
};

Which, as you pointed out, could allow the user to set the selector.

However, at the beginning of the code, he wrote...

var selector = 'body';

... which renders the previous function useless. It always appends to the <body>.

Solution: Download the library and create your own version, changing...

var selector = 'body';

... for just:

var selector;

With that change you can pass your selection using selector().

Here is a demo, I'm using a bl.locks from the same author of the library. I copied the library and changed the mentioned variable. In the HTML, I created a div with a class .foo before a paragraph with a lorem ipsum. Then, I selected the div with:

var gantt = d3.gantt().selector(".foo").taskTypes(taskNames).etc...

You can see (inspecting the page) that the chart is appended to the div, not to the body: http://bl.ocks.org/anonymous/raw/84385e7c6ac859ad24feb3662e46e3fd/

Actually, you don't even need to inspect the page: if it was appended to the body the lorem ipsum would be above the chart, not below, as it is.


问:
How can I check if element is present in laravel dusk test?
In the below code, I want to check if the element is present at XPath, then only it should execute code.

```<code>if($browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div[2]/div/table/tbody/tr['.$i.']/td[2]'))!==null)
{
    $sort=$browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div22]/div/table/tbody/tr['.$i.']/td[2]'))->gettext();
echo $sort;
}
</code>```

Or else please suggest if there is another way to check element is present  in laravel dusk.
P.S. I tried whenAvailable method but it couldn't help me in this case.

答:
When I want to check to see if an element exists, I usually do something like this:</p>

```<code>$this->browse(function (Browser $browser) {
    $this->assertNotNull($browser->element('#idString'));
}
</code>```

Body:
In the below code, I want to check if the element is present at XPath, then only it should execute code.

if($browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div[2]/div/table/tbody/tr['.$i.']/td[2]'))!==null)
{
    $sort=$browser->driver->findElement(WebDriverBy::xpath('/html/body/div[1]/div/section/div[3]/div22]/div/table/tbody/tr['.$i.']/td[2]'))->gettext();
echo $sort;
}

Or else please suggest if there is another way to check element is present  in laravel dusk.
P.S. I tried whenAvailable method but it couldn't help me in this case.

Body:
When I want to check to see if an element exists, I usually do something like this:

$this->browse(function (Browser $browser) {
    $this->assertNotNull($browser->element('#idString'));
}


问:
Angular 4 - create new Child Component in Parent with DI
I have an array of child components which are displayed with an *ngFor.
My child components now require a DataService to be injected. How do I create a new ChildComponent() when the compiler now complains about needing an instance of the DataService for the constructor?

Parent Component:

```<code>import { Component, OnInit } from '@angular/core';
import {SkipComponent} from "../skip/skip.component";
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-skips',
  templateUrl: './skips.component.html',
  styleUrls: ['./skips.component.css'],
  providers: [ DataService ]
})
export class SkipsComponent implements OnInit {

  public childItems: SkipComponent[] = [new SkipComponent()];

  public removeSkip(skip){

    var index = this.childItems.findIndex((elt) => (elt===skip));
    if (index != -1) {
      this.childItems.splice(index, 1);
    }
  }

  public onAdd(){
    this.childItems.push(new SkipComponent());
  }

  constructor() {
  }

  ngOnInit() {
  }
</code>```

Child Component:

```<code>import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-skip',
  templateUrl: './skip.component.html',
  styleUrls: ['./skip.component.css'],
  providers: [ DataService ]
})
export class SkipComponent implements OnInit {

  @Input() skip: any;

  @Output()
  onSkipRemove: EventEmitter<any> =  new EventEmitter();

  containers: any[];

  public removeSkip(){
    this.onSkipRemove.emit(
      this.skip
     )
  }

  constructor(private dataService: DataService) {
    this.dataService.getContainers().subscribe(res=>this.containers=res);
  }

  ngOnInit() {
  }

}
</code>```

答:
The DI happens when instantiated by the framework, when you explicitly instantiate a SkipComponent with the new operator, you need to pass in the service. So your solution will be:

In the top level (SkipsComponent) get a hold of the DataService:

```<code>constructor(private dataServices: DataService){}
</code>```

and then when you create SkipComponent pass it to the constructor:

```<code>this.childItems.push(new SkipComponent(this.dataService));
</code>```

Body:
I have an array of child components which are displayed with an *ngFor.
My child components now require a DataService to be injected. How do I create a new ChildComponent() when the compiler now complains about needing an instance of the DataService for the constructor?

Parent Component:

import { Component, OnInit } from '@angular/core';
import {SkipComponent} from "../skip/skip.component";
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-skips',
  templateUrl: './skips.component.html',
  styleUrls: ['./skips.component.css'],
  providers: [ DataService ]
})
export class SkipsComponent implements OnInit {

  public childItems: SkipComponent[] = [new SkipComponent()];

  public removeSkip(skip){

    var index = this.childItems.findIndex((elt) => (elt===skip));
    if (index != -1) {
      this.childItems.splice(index, 1);
    }
  }

  public onAdd(){
    this.childItems.push(new SkipComponent());
  }

  constructor() {
  }

  ngOnInit() {
  }

Child Component:

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';
import { DataService } from '../services/data.service';

@Component({
  selector: 'app-skip',
  templateUrl: './skip.component.html',
  styleUrls: ['./skip.component.css'],
  providers: [ DataService ]
})
export class SkipComponent implements OnInit {

  @Input() skip: any;

  @Output()
  onSkipRemove: EventEmitter<any> =  new EventEmitter();

  containers: any[];

  public removeSkip(){
    this.onSkipRemove.emit(
      this.skip
     )
  }

  constructor(private dataService: DataService) {
    this.dataService.getContainers().subscribe(res=>this.containers=res);
  }

  ngOnInit() {
  }

}

Body:
The DI happens when instantiated by the framework, when you explicitly instantiate a SkipComponent with the new operator, you need to pass in the service. So your solution will be:

In the top level (SkipsComponent) get a hold of the DataService:

constructor(private dataServices: DataService){}

and then when you create SkipComponent pass it to the constructor:

this.childItems.push(new SkipComponent(this.dataService));


问:
Parse JSON data in swift
I am trying to parse my json data in swift 3.0. I am using Alamofire 4.0+
Here is my json

```<code>{
"token":

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

"user":
[{"user_id":13,"user_first_name":"Himanshu","user_last_name":"Srivastava","full_name":"Himanshu Srivastava"}]
}
</code>```

Here is my model class to hold these values

```<code>import Foundation
import ObjectMapper
class LoginResult:Mappable{
    var token:String?
    var expires:Double?
    var users:[[String:Any]]?
    required init?(map:Map){

    }

    func mapping(map:Map)->Void{
        self.token <- map["token"]
        self.expires <- map["expires"]
        self.users <- map["user"]
    }
}
</code>```

None of the solution available on internet worked for me. How can I parse this json and map to the model class?
Any help here?

答:
Here is the answer with map replaced by dictionary. Don't forget to handle error or unwrap carefully :)</p>

```<code>let str = "{\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\": 1504428378111,\"user\": [{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]

    //Pass this json into the following function
}catch let error{

}

func mapping(json:[String: Any]?)->Void{
    self.token <- json?["token"] as? String
    self.expires <- json?["expires"] as? Double
    self.users <- json?["user"] as? [[String: Any]]
}
</code>```

Title: Parse JSON data in swift

Body:
I am trying to parse my json data in swift 3.0. I am using Alamofire 4.0+
Here is my json

{
"token":

"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80",

"expires": 1504428378111,

"user":
[{"user_id":13,"user_first_name":"Himanshu","user_last_name":"Srivastava","full_name":"Himanshu Srivastava"}]
}

Here is my model class to hold these values

import Foundation
import ObjectMapper
class LoginResult:Mappable{
    var token:String?
    var expires:Double?
    var users:[[String:Any]]?
    required init?(map:Map){

    }

    func mapping(map:Map)->Void{
        self.token <- map["token"]
        self.expires <- map["expires"]
        self.users <- map["user"]
    }
}

None of the solution available on internet worked for me. How can I parse this json and map to the model class?
Any help here?

Body:
Here is the answer with map replaced by dictionary. Don't forget to handle error or unwrap carefully :)

let str = "{\"token\": \"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE1MDQ0MjgzNzgxMTF9.CNonyvtQbRgaqqkdPO5KwqpVaUmlGrpaTqlBxmvaX80\",\"expires\": 1504428378111,\"user\": [{\"user_id\":13,\"user_first_name\":\"Himanshu\",\"user_last_name\":\"Srivastava\",\"full_name\":\"Himanshu Srivastava\"}]}"

let data = str.data(using: .utf8)

do{
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [String: Any]

    //Pass this json into the following function
}catch let error{

}

func mapping(json:[String: Any]?)->Void{
    self.token <- json?["token"] as? String
    self.expires <- json?["expires"] as? Double
    self.users <- json?["user"] as? [[String: Any]]
}