Skip to content
Advertisement

How to unit test methods together with its constraint validators (which some should be mocked out)?

My app has a service layer which is composed by CDI applications scoped beans:

JavaScript

When a method gets called, an interceptor (in my case BValInterceptor.class from Apache BVal) checks if the method contract is respected by checking the annotations and validating the parameters accordingly.

As you can see, there are some custom constraints like @SectionExists, @PostExists that may hit the database:

JavaScript

What I’d like to do is to unit test my business methods (getpost, delete, newPost) together with its validators. The validators that may hit the database should be mocked (or their dependency should be mocked).

How can I achieve this? How could I make injections (and mock injections) work for validators in unit tests?

Here what I’m using:

  • TomEE 8.0.8
  • Apache BVal for Bean Validation JSR 303/JSR380 (included in TomEE)
  • Apache OpenWebBeans for CDI (included in TomEE)
  • JUnit 5
  • Mockito

I can use OpenEJB’s ApplicationComposer or Arquillian to run an embedded container. However, I’ve never used Arquillian.

Advertisement

Answer

In the end I went for this really cool library (cdimock) that does exactly what i needed: put the mocks in a custom CDI scope so that the same mock instances can be injected in other beans inside the test case. Such thing can also be achievable with cdi-unit @Produces @Mock annotations (Although i haven’t tried it personally since it only supports Weld)

This is my test class’ code:

JavaScript

In the code i’m using OpenEJB’s Application Composer but i can easily switch to any embedded CDI container

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement