我正在使用spring mvc测试框架进行单元测试。如何创建存储库类的bean
下面是我的源代码: 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。 请教我如何使用Java(而不是xml)创建存储库类的bean。
您是否导入了Spring JPA配置类?你如何配置JPA?你可以显示配置Spring JPA的类(有休眠)吗? – Shaheer
在我的项目中,没有Spring JPA配置类,只有Controller,Service,Repository和Domain类。我使用spring mvc框架。运行应用程序没有问题,但是在运行测试代码时发生了上述错误。 – NhanQV
使用@EnableJpaRepositories注释为为“单元测试”上下文定义的存储库接口创建实例和bean定义。 – Shaheer