Mongock (Mongobee) and Spring Boot in unit test

3.9k Views Asked by At

I have the following dummy class:

@Document("items")
static class Item {
    int i;

    public Item() {
    }

    public Item(int i) {
        this.i = i;
    }

    public int getI() {
        return i;
    }
}

And here's a simple @Changeset:

//@Autowired
@ChangeSet(order = "001", id = "add_items", author = "tester")
public void changeset1(MongoTemplate mongoTemplate) {
    for (int i = 0; i < NUM_OF_DB_ITEMS; i++) {
        mongoTemplate.insert(new Item(i));
    }
}

After @Changeset is called, the unit test is running (Notice that mongoTemplate is @Autowired)

@Test
public void test() {
    List<Item> items = mongoTemplate.findAll(Item.class);
    System.out.println(items);
}

Problem: I'm getting zero items from findAll()

I found that when I'm adding @Autowired to changeset1() it does work (commented above) - I'm getting all items.

Can you explain why? In the examples, I don't see they need to @Autowired

Should I even do that? I mean, can it damage the locking mechanism of Mongock?

3

There are 3 best solutions below

0
Longer On

Without your complete code, it's hard to figure out what went wrong. Most likely spring configuration isn't configured correctly, so without autowire annotation, mongoTemplate isn't instantiated properly in Spring container. If you care to track deeper into the MongoTemplate source code and comparing the execution path before the annotation change and after it, you will find out why.

I would suggest following their example to find out anything missing in your project. https://github.com/cloudyrock/mongock-samples/tree/master/samples-mongock-spring/sample-mongock-spring-v2

0
Mozart Araujo Filho On

I had the same issue and in my case the bean creator/runner had a mispelled package name for the builder atribute "changeLogScanPackage"

@Bean
public SpringMongock springMongock(MongoTemplate mongoTemplate, Environment springEnvironment) {
  return new SpringMongockBuilder(mongoTemplate, "changeLogScanPackage")
        .setSpringEnvironment(springEnvironment)
      .setLockQuickConfig() OR .setLockConfig(3, 4, 3) 
       ...other setters
      .build();
}
1
Kyrstellaine On

I realize this is an old question, but per Mongock documentation, you need to use MongockTemplate, not MongoTemplate