My app has a service layer which is composed by CDI @ApplicationScoped
beans. This is a class extracted from my project:
@ApplicationScoped
public class PostService {
@Inject private PostRepository postRepo;
@Inject private UserRepository userRepo;
@Inject private SectionRepository sectionRepo;
@Inject private LoggedInUser loggedInUser;
@Transactional
public PostDto getPost(@PostExists int id){
Post p = postRepo.findById(id);
//create post DTO from p
return post;
}
@Transactional
public void delete(@PostExists int id){
postRepo.remove(postRepo.findById(id));
}
@RolesAllowed({"user","admin"})
@Transactional
public int newPost(@NotBlank @Max(255) String title,
@Max(2000) String body,
@SectionExists String sectionName){
User user = userRepo.getByName(loggedInUser.getUsername());
Section section = sectionRepo.getByName(sectionName);
Post post = new Post();
post.setTitle(title);
post.setContent(body == null || body.isBlank() ? "" : body);
post.setAuthor(user);
post.setSection(section);
post.setType(TEXT);
return postRepo.insert(post).getId();
}
}
PostService
is a class that contains the business logic for the manipulation of the Post
domain objects.
Many things are actually delegated to other classes:
- Dependency injection by the @Inject annotations
- Parameter validation by means of the Constraint validator annotations to define preconditions (Some validators may hit the database)
- The
@Transactional
annotation decorates the method adding transaction boundaries - Authorization checking by means of
@RolesAllowed
But with all these dependencies from external mechanisms, and with this few lines of code that actually hit my business logic, how can I test this class? Does it make sense to unit test this class, or should I go directly with integration testing with an embedded OpenEJB container? (I'm currently using TomEE)
I'd like to unit test my service classes, in order to maintain consistency on my API in terms of behaviour. However, not using an embedded EE container would mean ignoring some mechanisms that are actually applied in the "main" code. How should i proceed?