我对Spring Boot有点新意,出于学习目的,我使用内存数据库(H2)编写了一个简单的REST API。
当我实际运行应用程序时,一切正常:数据库被加载到内存中并使用我提供的import.sql文件填充,我的端点 做他们应该做的事。现在我正在尝试编写一个控制器测试,它应该调用“通过id查找东西”端点。这就是问题所在: 当我运行此测试时,它没有在数据库中找到任何条目并且失败,即,似乎我的数据库尚未在启动时填充。我不知道发生了什么 因为,正如我所说的,当我实际运行应用程序并使用Postman测试它时,一切都在内存中并按预期工作。
为了在测试场景中正确填充数据库,我该怎么做?
仅供参考,我已阅读this文章(非常有用的顺便说一句),虽然他使用另一种方法来填充他的数据库,但他没有对他的测试需求做任何特别的事情。使用Postman和测试时,一切都运行良好。这是我试图完成的。
任何帮助都会得到真正的赞赏。我做了很多研究,尝试了很多东西,但无济于事。
这些是我认为相关的文件:
** / scr / main / resources
下的application.propertiesserver.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
**我的控制器类和我想测试的find方法。
@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);
}
}
**我的控制器测试类和find方法:
@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初始化日志(请注意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$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)
编辑:我的项目结构:
答案 0 :(得分:1)
JUnit问题(基本上是断言问题)说没有ID意味着两件事:
你的情况是第二个,因为ID我可以从你看到实体,我也看到你有创建-drop hibernate DDL,但请注意,它不是用虚拟信息填充DB而只是创建它。
因此,这意味着您需要使用一些虚拟数据填充DB。
为此,您可以添加名为&#34; import.sql&#34;的文件。到您的类路径(例如,如果您正在使用Maven / Gradle项目布局,则在src / main / resources中)。
答案 1 :(得分:1)
您需要在运行Unit测试之前定义虚拟数据,您给出的链接在DemoApplication.class中执行,并使用测试类上的@ContextConfiguration加载它。您的代码中缺少该部分。在您的单元测试中,import.sql在您提及之前不会运行。可以使用@Sql批注完成
@Sql({ "import.sql" })
对于单元测试,您不需要进行数据库调用,通常在集成测试中完成。对于junits,您可以模拟您的服务电话,如下所示
when(emailService.buscar(anyInt()).thenReturn(new Email());