我正在使用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