I'm developing a Spring Boot application following TDD methodology. I've created the main classes (controller, service and repository) this way:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CrimeServiceImpl implements CrimeService{
@Autowired
private CrimeRepository repository;
...
Controller:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class CrimeController {
@Autowired
private CrimeServiceImpl service = new CrimeServiceImpl();
Repository:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface CrimeRepository extends JpaRepository<Crime, Long>{
}
This is the project structure:
If I run the application normally, no error. The classes' methods are empty. Then I've created a test class like this:
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = CrimeServiceImpl.class)
@ComponentScan("com.springmiddleware")
@AutoConfigureMockMvc
@SpringBootTest
public class TestCrimeService {
//Calling method getAllCrimes works
@Test
public void returnAllCrimesExists() throws NoSuchMethodException, SecurityException {
CrimeServiceImpl csi = mock(CrimeServiceImpl.class);
assertTrue(CrimeServiceImpl.class.getMethod("getAllCrimes")!=null);
}
And if I run this, the following error is shown and the test fails:
NoSuchBeanDefinitionException: No qualifying bean of type 'com.springmiddleware.repository.CrimeRepository' available: expected at least 1 bean which qualifies as autowire candidate.
I've checked all annotations and it seems to me that all is ok, and I thought if I missed something, even in the normal run the application would fail. What did I got wrong?
Aucun commentaire:
Enregistrer un commentaire