4

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?

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.