Chris
Chris

Reputation: 407

Spring Web Service Test with MongoDB

I'm writing service tests for my Spring Boot Web application that acts as an interface to MongoDB. Ideally, my service test will test each component of my Spring application before finally hitting a Mocked MongoTemplate. The following code uses a MockMvc to hit my web endpoints.

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class)
@AutoConfigureDataMongo
public class MyControllerServiceTest {

  @Autowired
  private MockMvc mvc;

  @Autowired
  private MongoTemplate mongoTemplate

  @SpyBean
  private MyMongoRepository myMongoRepository;

  @Test
  public void createTest() {
    MyObject create = new MyObject()

    given(this.myMongoRepository.insert(create));

    this.mvc.perform(post("localhost:8080/myService")...)...;
  }
}

MyController contains an @Autowired MyMongoRepository, which in turn implements MongoRepository and necessitates a mongoTemplate bean. This code executes properly only if a running MongoDB instance can be found (this example is more of an integration test between my service and MongoDB).

How can I mock out MongoTemplate while still using my MockMvc?

Upvotes: 4

Views: 7170

Answers (2)

Abbas Hosseini
Abbas Hosseini

Reputation: 747

You need to add the following line to your test unit:

@MockBean
private MongoTemplate mongoTemplate;

For example, your class should look like this:

@RunWith(SpringRunner.class)
@WebMvcTest(MyController.class, excludeAutoConfiguration = EmbeddedMongoAutoConfiguration.class)
public class MyMvcTests {

  @Autowired
  private MockMvc mvc;

  @MockBean
  private MyRepository repository;

  @MockBean
  private MongoTemplate mongoTemplate;

  @Test
  public void someTest() {}
}      

You can find a complete Spring Boot application that include Integration and Unit tests here.

Upvotes: 3

pvpkiran
pvpkiran

Reputation: 27078

I think a better approach to test would be to test your web layer(controller) and your service layer separately.

  1. For testing your web layer you can use MockMvc and you can mock your service layer.

  2. For testing your service layer which in turn talks to mongo, you can use a Fongo and nosqlunit.

    Some examples here
    https://arthurportas.wordpress.com/2017/01/21/sample-project-using-spring-boot-and-mongodbfongo-and-test-repository-with-nosqlunit/

    https://github.com/JohnathanMarkSmith/spring-fongo-demo

Upvotes: 0

Related Questions