I'm doing unit test using spring mvc test framework.
The following is my source code: 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();
}
}
When I run test, the following error is displayed nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException
I know the exception occurred because MyService didn't find any bean of MyRepository. But I don't know how to create a bean of repository. Please teach me how to create a bean of repository class using Java (not xml).
You need to enable the JPA repositories in your config class, specify the package that contains the repositories as below
@Configuration
@EnableJpaRepositories(basePackages = {
"com.example.repository"
})
public class TestConfig {
@Bean
public MyService myService() {
// set properties, etc.
return new DestinationServiceImpl();
}
}
Edit: looks like you haven't defined entityManager, and dataSource. Refer to a tutorial here and also answer to similar question here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With