UnsatisfiedDependencyException в проектах SpringMVC и MongoDB

Я работаю над приложением Spring MVC и MongoDB.

Мой API работает нормально, но я хотел бы создать интеграционный тест с Fongo, чтобы проверить сохранение файла и после получения этого файла моими службами.

Я уже пробовал, но когда я добавил @Autowired в моем классе обслуживания он вернул UnsatisfiedDependencyException, Мой тестовый класс:

@ActiveProfiles({"test"})
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
    locations = {
            "classpath*:config/servlet-config.xml",
            "classpath*:config/SpringConfig.xml"})
@WebAppConfiguration
public class IntegrationTest {
@Autowired   // returns UnsatisfiedDependencyException
private FileService fileService;

@Before
@Test
public void setUp() throws IOException {
Fongo fongo = new Fongo("dbTest");
DB db = fongo.getDB("myDb");
}

@Test
public void testInsertAndGetFile() throws IOException{

    //create a file document in order to save
    File file = new File();
    file.setId("1");
    file.setFileName("test1");
    file.setVersionId("1");

    //save the file
    String id = fileService.storeFile(file);

    //get the file
    File fileDocument= fileService.getFileById("1");

    //check if id is the file id which is expected
    assertEquals(fileDocument.getId(), "1");
}
}

и я получаю это сообщение журнала:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.ots.openonefilesystem.integration.IntegrationTest': Unsatisfied dependency expressed through field 'fileService'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.myproject.service.FileService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean found for dependency [com.myproject.service.FileService]: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

Я использую конфигурацию XML.

Как я могу решить мою ошибку тестирования? В моем классе обслуживания FileService я положил @ServiceТем не менее, кажется, что Spring ожидал по крайней мере 1 боб, который квалифицируется как кандидат на автопровод.

Также, если я удаляю @Autowired, журнал возвращает NullpointerException при сохранении получаю файл, как и ожидалось.

PS: я использую springFramework 4.3.3.RELEASE, spring-data-mongodb 1.9.5.RELEASE

Заранее спасибо!

1 ответ

Решение

Мне пришлось настроить Mock Database (Fongo), чтобы @Autowired FileService, Это я сделал через @ContextConfiguration(classes = {MockDatasourceConfig.class})

Итак, правильный класс тестовых приборов следующий:

@ActiveProfiles({"test"})
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {MockDatasourceConfig.class})
@WebAppConfiguration
public class IntegrationTest{

@Autowired
private FileService fileService;

@Test
public void testInsertAndGetFile() throws IOException{

    //create a file document in order to save
    File file = new File();
    file.setId("1");
    file.setFileName("test1");
    file.setVersionId("1");
    //save the file and return his id
    String id = fileService.storeFileGeneral(file);
    //get the file
    FileDocument fileDocument= fileService.getFileById(id);
    //check that the file isn't null
    assertNotNull(fileDocument);
    //check if id is the file id which is expected
    assertEquals(fileDocument.getId(), id);
    assertEquals(fileDocument.getFileName(), "test1");
}
}

и MockDatasourceConfig класс следующий:

@Profile({"test"})
@Configuration
@PropertySource("classpath:mongo.properties")
@ComponentScan(basePackageClasses = {File.class})
@EnableMongoRepositories(basePackageClasses = RepositoryPackageMarker.class)
public class MockDatasourceConfig extends AbstractMongoConfiguration {

@Autowired
Environment env;

@Override
protected String getDatabaseName() {
    return env.getProperty("mongo.dbname", "myDb");
}

@Override
public Mongo mongo() throws Exception {
    return new Fongo(getDatabaseName()).getMongo();
}

@Bean
public GridFsTemplate gridFsTemplate() throws Exception {
    return new GridFsTemplate( mongoDbFactory(),mappingMongoConverter());
}
}

PS: с полезным советом @M.Deinum

Другие вопросы по тегам