I have a stateless EJB that uses @PersistenceContext
with a EntityManager
, I'm writing a cucumber step definitions class that uses this repository to perform steps in testing finding users based upon supplied criteria.
So for example
@Stateless
public class UserRepository {
@PersistenceContext
private EntityManager em;
public void add(String userName) {
User user = new User(userName);
em.persist(user);
}
public List<User> findByName(String userName) {
return em.createQuery("Select u from User as u WHERE u.name LIKE :userName").setParameter("userName", userName).getResultList();
}
}
And a feature file that looks something like
Feature: Search
Given a user with the name 'Jason Statham'
And another user with the name 'Bill Gates'
And another user with the name 'Larry Page'
When the customer searches for a user with the name 'Jason'
Then 1 users should have been found
And User 1 should have a name of 'Jason Statham'
And a steps definition class
public class SearchStepsDefinitions {
private List<User> userList = new ArrayList<>();
private UserService userService = new UserService();
@Given(value = ".+user with the name '(.+)'$")
public void a_user_with_the_name(final String userName) {
userService.add(userName);
}
@When(value = "^the customer searches for a user with the name '(.+)'$")
public void the_customer_searches_for_a_user_with_the_name(final String name) {
userList = userService.findByName(name);
}
@Then(value = "(\\d+) users should have been found$")
public void users_should_have_been_found(final int userCount) {
assertThat(userList.size(), equalTo(userCount));
}
@Then(value = "User (\\d+) should have a name of '(.+)'$")
public void should_have_a_name_of(final int position, final String name) {
assertThat(userList.get(position - 1).getName(), equalTo(name));
}
}
Now I understand that as the Repository is an EJB the EntityManager
is injected via the @PersistenceContext
.
My question is in the steps definition how should I be dealing with this dependency? Should I be mocking it and injecting this mock into the UserRepository
, or should the UserRepository
have a setter for the EntityManager
and use a EntityManagerFactory
to create one in the SearchStepsDefinitions
?
Aucun commentaire:
Enregistrer un commentaire