【发布时间】:2019-07-11 20:33:13
【问题描述】:
我有我的 java spring boot 应用程序,我想使用 mockmvc 编写一些测试;所以这是测试类:
@RunWith(SpringRunner.class)
@WebMvcTest(controllers = {IndexController.class})
@ComponentScan(basePackages={"com.sherlock.discoteque"})
@EnableJpaRepositories("com.sherlock.discoteque.repository")
@EntityScan(basePackages={"com.sherlock.discoteque"})
public class DiscotequeApplicationTests {
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.standaloneSetup(webApplicationContext).build();
}
@Test
public void testAlbumInfo() throws Exception{
this.mockMvc.perform(get("/")).andExpect(status().isOk());
}
}
但是当我执行代码时出现以下错误消息:
com.sherlock.discoteque.controller.AlbumController 中的字段 albumRepository 需要一个无法找到的“javax.persistence.EntityManagerFactory”类型的 bean。
注入点有以下注解: - @org.springframework.beans.factory.annotation.Autowired(required=true)
行动:
考虑定义一个 bean 类型 'javax.persistence.EntityManagerFactory' 在您的配置中。 ... 引起:org.springframework.beans.factory.UnsatisfiedDependencyException: 创建名为“albumController”的 bean 时出错:不满意 通过字段“albumRepository”表达的依赖关系;嵌套异常 是 org.springframework.beans.factory.BeanCreationException: 错误 创建名为“albumRepositoryImpl”的bean:注入 持久性依赖失败;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:否 'javax.persistence.EntityManagerFactory' 类型的限定 bean 可用的 引起:org.springframework.beans.factory.BeanCreationException: 错误创建名为“albumRepositoryImpl”的 bean:注入 持久性依赖失败; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: 否 'javax.persistence.EntityManagerFactory' 类型的限定 bean 可用
这很奇怪,考虑到没有测试类,一切都可以正常工作。这是类 AlbumRepositoryImpl
public class AlbumRepositoryImpl implements AlbumRepositoryCustom {
private final static String RECENT_ALBUMS_QUERY = "select * from album order by createdate desc limit ?";
@PersistenceContext
public EntityManager entityManager;
@Override
public List<Album> getRecentAlbums(int size) {
if(size<1){
throw new IllegalArgumentException();
}
Query query = entityManager.createNativeQuery(RECENT_ALBUMS_QUERY, Album.class);
query.setParameter(1, size);
return query.getResultList();
}
}
在 AlbumController 内部我确实有该属性
@Autowired
private AlbumRepository albumRepository;
我也有 AlbumRepository 接口(从 JpaRepository 扩展)。我真的不知道该怎么做才能使 Web 应用程序在测试中运行,有人可以帮助我吗?
【问题讨论】:
标签: java unit-testing spring-boot junit spring-data-jpa