【发布时间】:2017-10-06 08:39:37
【问题描述】:
我正在开发一个 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 个符合自动装配候选资格的 bean。
此外,如果我删除了@Autowired,则在保存获取文件时,日志将返回NullpointerException,正如预期的那样。
PS:我用的是springFramework 4.3.3.RELEASE,spring-data-mongodb 1.9.5.RELEASE
提前谢谢你!
【问题讨论】:
-
所以你在你的测试类中创建了一个
Fongo的新实例,并期望 Spring 使用它来自动连接......这显然不会发生,你必须在你的spring 上下文,因此 Spring 可以自动连接它。 -
感谢您的即时回复。我可以理解这一点,所以我尝试了另一种解决方案,在这个link 中,但是当我不添加@Autowired 时,我正在接收
NullPointerException,当我使用它时,我收到UnsatisfiedDependencyException -
当然它会导致
NullPointer...您需要配置Fongo并将其用作mongo 设置中的驱动程序(或数据库)。如前所述,您需要一个测试配置。 -
With
@ContextConfiguration(classes = {MockDatasourceConfig.class})没有弥补? -
它会启动,但只要你不让它覆盖你的默认 mongo 实例,它就不会工作,并且删除
@Autowired会破坏事情。
标签: mongodb spring-mvc exception integration-testing fongo