我正在使用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。
答案 0 :(得分:1)
您需要在配置类中启用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