在单元测试期间使用spring-data-monogdb读取fongo时未设置Id字段

时间:2016-05-03 14:14:10

标签: java mongodb unit-testing spring-boot fongo

我有以下问题: 我有一个spring-boot(1.3.3)应用程序,它使用mongodb作为存储。所有使用mongo存储库的真正mongodb工作正常。但是对于单元测试,我们尝试使用 fongo 来在每台服务器上都没有安装mongodb。测试的大多数部分也适用于fongo,但是当我从数据库(fongo)加载对象时,没有设置具有id的字段。 有没有其他人经历过类似的?感谢您提供所有帮助!

文件:

@Document
public class SystemEvent {

    @Id
    private String id;

    private String oid;

    private String description;

    private String type;

    private String severtity;

    public SystemEvent(){
    }

    // getter/setter

}

存储库:

@Repository
public interface SystemEventRepository extends MongoRepository<SystemEvent, String> {

}

测试

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = MongoFongoApplication.class)
public class MongoFongoApplicationTests {

    @Test
    public void contextLoads() {
    }

    @Autowired
    SystemEventRepository systemEventRepository;

    @Test
    public void testRepo() {
        SystemEvent info1 = systemEventRepository.save(new SystemEvent("DESC 1", "TYPE 1", "INFO"));
        SystemEvent info2 = systemEventRepository.save(new SystemEvent("DESC 2", "TYPE 2", "INFO"));
        List<SystemEvent> all = systemEventRepository.findAll();

        assertThat(all.size(), is(2)); // WORKS FINE

        // -----

        SystemEvent systemEvent = systemEventRepository.findOne(info1.getId());

        assertThat(systemEvent, notNullValue());  // WORKS FINE
        assertThat(systemEvent.getId(), notNullValue()); // FAILS
    }

    @Configuration
    public static class TestConfig extends AbstractMongoConfiguration {
        @Override
        protected String getDatabaseName() {
            return "test";
        }

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

}

1 个答案:

答案 0 :(得分:0)

尝试在Document model类中为您的Id字段添加这些内容。这应该可以解决您的问题。

@Id
@Field(value = GdnBaseMongoEntity.ID)
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name = "system-uuid", strategy = "uuid2")
private String id;

对于 GeneratedValue ,您需要为 javax持久性API 添加依赖项。您可以在 pom.xml 文件

中添加此内容
<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

对于build.gradle

compile group: 'org.hibernate.javax.persistence', name: 'hibernate-jpa-2.0-api', version: '1.0.0.Final'