Spring Boot应用程序上的设置2数据源,在测试期间仅获取NullPointerException。
我将省略application.properties,Book模型,BookRepository(Spring Data JPA),因为它是非常标准的东西,并且会使这个问题变得太长了。
BookController。 ->这是我正在测试的方法
@GetMapping()
public Iterable<Book>getBooks(){
log.info("Book controller accessed");
return this.bookService.findAll(); // Returning null during test
}
BookDatasourceConfig
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
basePackages = {"com.example.multipledatasource.book"},
entityManagerFactoryRef = "bookEntityManagerFactory",
transactionManagerRef = "bookTransactionManager"
)
public class BookDatasourceConfig {
@Bean(name="db2Datasource")
@ConfigurationProperties(prefix = "db2.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
// Create EntityManager
@Bean(name="bookEntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
@Qualifier("db2Datasource") DataSource dataSource){
// We are using Spring Data JPA so we want to create the entity automatically we must set some properties
Map<String, Object> properties = new HashMap<>();
properties.put("hibernate.hbm2ddl.auto", "create-drop");
properties.put("spring.jpa.database-platform", "org.hibernate.dialect.MySQL5Dialect");
// Build EntityManager
// Provide the base packages to scan, specify User entity
return builder.dataSource(dataSource)
.properties(properties)
.packages("com.example.multipledatasource.book")
.persistenceUnit("Book")
.build();
}
// Transaction manager
@Bean(name="bookTransactionManager")
public PlatformTransactionManager transactionManager(@Qualifier("bookEntityManagerFactory") EntityManagerFactory entityManagerFactory){
return new JpaTransactionManager(entityManagerFactory);
}
}
测试
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@WebAppConfiguration
public class BookControllerTest {
@Rule
public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation("target/generated-snippets");
private MockMvc mockMvc;
private RestDocumentationResultHandler docHandler;
@InjectMocks
private BookController bookController;
@Before
public void setUp() throws Exception {
this.docHandler = document("{ClassName}/{methodName}", preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()));
this.mockMvc = MockMvcBuilders.standaloneSetup(bookController)
.apply(documentationConfiguration(this.restDocumentation))
.alwaysDo(this.docHandler)
.build();
}
@Test
public void getBooks() throws Exception {
this.mockMvc.perform(get("/book")
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk());
}
问题:
从跟踪中可以看到,测试开始时,Hibernate将创建表并按预期插入数据。但是,当进程在尝试访问数据库时到达控制器方法时,我得到了Null异常。
可能是什么问题?
StackTrace
2019-03-15 15:52:38 INFO org.hibernate.dialect.Dialect []]: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate:
drop table if exists Book
Hibernate:
create table Book (
id integer not null auto_increment,
name varchar(255),
primary key (id)
) engine=MyISAM
2019-03-15 15:52:39 INFO o.h.t.schema.internal.SchemaCreatorImpl []]: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@71e2843b'
2019-03-15 15:52:39 INFO o.s.o.j.LocalContainerEntityManagerFactoryBean []]: Initialized JPA EntityManagerFactory for persistence unit 'Book'
2019-03-15 15:52:42 INFO c.e.m.BookControllerTest []]: Started BookControllerTest in 10.472 seconds (JVM running for 12.486)
Hibernate:
insert
into
Book
(name)
values
(?)
Hibernate:
insert
into
Book
(name)
values
(?)
2019-03-15 15:52:42 INFO c.e.multipledatasource.config.AppConfig []]: Type: class com.example.multipledatasource.book.Book
2019-03-15 15:52:42 INFO c.e.multipledatasource.config.AppConfig []]: Book data setup: [Book{id=1, name='Servlets and JPA'}, Book{id=3, name='MySql'}]
2019-03-15 15:52:43 INFO o.s.mock.web.MockServletContext []]: Initializing Spring TestDispatcherServlet ''
2019-03-15 15:52:43 INFO o.s.t.web.servlet.TestDispatcherServlet []]: Initializing Servlet ''
2019-03-15 15:52:43 INFO o.s.t.web.servlet.TestDispatcherServlet []]: Completed initialization in 0 ms
2019-03-15 15:52:43 INFO c.e.m.book.BookController []]: Book controller accessed
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:166)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:133)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:182)
at com.example.multipledatasource.BookControllerTest.getBooks(BookControllerTest.java:56)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
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.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
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.restdocs.JUnitRestDocumentation$1.evaluate(JUnitRestDocumentation.java:63)
at org.junit.rules.RunRules.evaluate(RunRules.java:20)
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:251)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
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:190)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
at com.example.multipledatasource.book.BookController.getBooks(BookController.java:25)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:189)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:895)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:800)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1038)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)