我正在使用 spring mvc 测试框架进行单元测试。
以下是我的源代码: com.exmple.main
MyController.java
@Controller
public class MyController {
@Autowired
private MyService myService;
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
public Map<Object, Object> myControllerFunction(@RequestBody final Object jsonRequest) {
/* do something */
return response;
}
}
MyRepository.java
@Repository
public interface MyRepository extends JpaRepository<My, String> {
@Query(value="select * from my d where (d.start_date<to_date(:date,'YYYY/DD/MM')) and (d.end_date>to_date(:date,'YYYY/DD/MM'))", nativeQuery=true)
List<My> findByDate(@Param("date") String date);
}
MyService.java
public interface MyService {
List<My> findByDate(String date);
}
MyServiceImpl.java
@Service
public class MyServiceImpl implements MyService {
@Autowired
MyRepository destRepo;
@Override
public List<My> findByDate(String date) {
List<My> listDest = destRepo.findByDate(date);
return listDest;
}
}
com.example.test
MyControllerTest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfig.class})
@WebAppConfiguration
public class MyControllerTest {
private MockMvc mockMvc;
@Autowired
MyService myService;
@Autowired
protected WebApplicationContext webApplicationContext;
@Before
public void setup() throws Exception {
// this.mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void listAllMy() throws Exception {
}
}
TestConfig.java
@Configuration
public class TestConfig {
@Bean
public MyService myService() {
// set properties, etc.
return new MyServiceImpl();
}
}
当我运行测试时,显示以下错误 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException
我知道发生异常是因为 MyService 没有找到 MyRepository 的任何 bean。 但我不知道如何创建存储库 bean。 请教我如何使用 Java(不是 xml)创建存储库类的 bean。
最佳答案
您需要在配置类中启用 JPA 存储库,指定包含存储库的包,如下所示
@Configuration
@EnableJpaRepositories(basePackages = {
"com.example.repository"
})
public class TestConfig {
@Bean
public MyService myService() {
// set properties, etc.
return new DestinationServiceImpl();
}
}
编辑:看起来您还没有定义 entityManager 和 dataSource。引用a tutorial here并回答类似问题 here
关于java - 如何创建存储库类的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34987743/