当我 运行 我的单一测试时,内存中的 H2 是空的,但当我 运行 应用程序本身时它被填充
H2 in memory is empty when I run my unitary tests but it´s populated when I run the application itself
我对 Spring Boot 比较陌生,出于学习目的,我使用内存数据库 (H2) 编写了一个简单的 REST API。
当我实际 运行 应用程序时一切正常:数据库被加载到内存中并使用我提供的 import.sql 文件填充,我的端点
做他们应该做的事。现在我正在尝试编写一个应该调用 "find stuff by id" 端点的控制器测试。这就是问题所在:
当我 运行 这个测试时,它没有在数据库中找到任何条目并且失败了,也就是说,似乎我的数据库在启动时没有被填充。我不知道发生了什么
因为,正如我所说,当我实际 运行 应用程序并使用 Postman 对其进行测试时,一切都在内存中并按预期工作。
我应该怎么做才能在测试场景中正确填充我的数据库?
仅供参考,我阅读了 this 文章(顺便说一句,非常有用),尽管他使用另一种方法来填充他的数据库,但他并没有针对他的测试需求做任何特别的事情。使用 Postman 和测试时一切 运行 都很好。这就是我想要完成的。
任何帮助将不胜感激。我做了很多研究,尝试了很多东西,但都无济于事。
这些是我认为相关的文件:
** 我的 application.properties 在 /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
** 我的控制器 class 和我要测试的查找方法。
@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);
}
}
** 我的控制器测试 class 和查找方法:
@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());
}
}
** 我的邮箱模型
@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
}
** Spring Boot initialization log when I actually 运行 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
** JUnit 失败日志:
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.match(JsonPathResultMatchers.java:100)
at org.springframework.test.web.servlet.MockMvc.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.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.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=17=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.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)
编辑:我的项目结构:
project tree
JUnit 问题(基本上是断言问题)表示没有 ID 意味着两件事:
- 结果JSON不包含ID
- 结果JSON为空
你的情况是第二个,因为我可以从你的实体中看到 ID,而且我还看到你有 create-drop hibernate DDL,但请注意,它不是用虚拟信息填充数据库,而是创建它。
所以,这意味着您需要用一些虚拟数据填充数据库。
为此,您可以将名为 "import.sql" 的文件添加到您的类路径(即如果您使用的是 Maven/Gradle 项目布局,则在 src/main/resources 中)。
您需要在 运行 进行单元测试之前定义虚拟数据,您提供的 link 在 DemoApplication.class 中执行此操作并在测试中使用 @ContextConfiguration 加载它 class。你的 code.In 中缺少那部分你的单元测试 import.sql 不会 运行 直到你提到 it.It 可以使用 @Sql 注释
@Sql({ "import.sql" })
同样对于单元测试你不需要进行数据库调用,它通常在集成测试中完成。对于 junits,您可以如下所示模拟您的服务调用
when(emailService.buscar(anyInt()).thenReturn(new Email());
我对 Spring Boot 比较陌生,出于学习目的,我使用内存数据库 (H2) 编写了一个简单的 REST API。
当我实际 运行 应用程序时一切正常:数据库被加载到内存中并使用我提供的 import.sql 文件填充,我的端点 做他们应该做的事。现在我正在尝试编写一个应该调用 "find stuff by id" 端点的控制器测试。这就是问题所在: 当我 运行 这个测试时,它没有在数据库中找到任何条目并且失败了,也就是说,似乎我的数据库在启动时没有被填充。我不知道发生了什么 因为,正如我所说,当我实际 运行 应用程序并使用 Postman 对其进行测试时,一切都在内存中并按预期工作。
我应该怎么做才能在测试场景中正确填充我的数据库?
仅供参考,我阅读了 this 文章(顺便说一句,非常有用),尽管他使用另一种方法来填充他的数据库,但他并没有针对他的测试需求做任何特别的事情。使用 Postman 和测试时一切 运行 都很好。这就是我想要完成的。
任何帮助将不胜感激。我做了很多研究,尝试了很多东西,但都无济于事。
这些是我认为相关的文件:
** 我的 application.properties 在 /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
** 我的控制器 class 和我要测试的查找方法。
@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);
}
}
** 我的控制器测试 class 和查找方法:
@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());
}
}
** 我的邮箱模型
@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
}
** Spring Boot initialization log when I actually 运行 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
** JUnit 失败日志:
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.match(JsonPathResultMatchers.java:100)
at org.springframework.test.web.servlet.MockMvc.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.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.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access[=17=]0(ParentRunner.java:58)
at org.junit.runners.ParentRunner.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)
编辑:我的项目结构:
project tree
JUnit 问题(基本上是断言问题)表示没有 ID 意味着两件事:
- 结果JSON不包含ID
- 结果JSON为空
你的情况是第二个,因为我可以从你的实体中看到 ID,而且我还看到你有 create-drop hibernate DDL,但请注意,它不是用虚拟信息填充数据库,而是创建它。
所以,这意味着您需要用一些虚拟数据填充数据库。
为此,您可以将名为 "import.sql" 的文件添加到您的类路径(即如果您使用的是 Maven/Gradle 项目布局,则在 src/main/resources 中)。
您需要在 运行 进行单元测试之前定义虚拟数据,您提供的 link 在 DemoApplication.class 中执行此操作并在测试中使用 @ContextConfiguration 加载它 class。你的 code.In 中缺少那部分你的单元测试 import.sql 不会 运行 直到你提到 it.It 可以使用 @Sql 注释
@Sql({ "import.sql" })
同样对于单元测试你不需要进行数据库调用,它通常在集成测试中完成。对于 junits,您可以如下所示模拟您的服务调用
when(emailService.buscar(anyInt()).thenReturn(new Email());