R. Illger
R. Illger

Reputation: 21

Id field is not set when read out of a fongo using spring-data-monogdb during unit tests

I have the following problem: I have a spring-boot (1.3.3) application that uses a mongodb as storage. All works fine with a real mongodb using the mongo repositories. But for unit tests we try to use fongo to have not install a mongodb on every server. Most parts of the tests work also fine with fongo, but when i load an object form the database(fongo) the field with the id is not set. Has anyone else experienced a similar? Thanks in an advance for all your help!

Document:

@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:

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

}

Test:

@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();
        }
    }

}

Upvotes: 2

Views: 344

Answers (1)

lrathod
lrathod

Reputation: 1124

Try adding these for your Id field in Document model class. This should fix you problem.

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

For GeneratedValue you will need to add dependency for javax persistence API. you can add this in ur pom.xml file

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

For build.gradle

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

Upvotes: 0

Related Questions