First time using EasyMock and Spring together.
I have the test class:
@RunWith(EasyMockRunner.class)
public class ProjectServiceTest {
private ProjectRepository projectRepositoryMock;
private ProjectService service;
@Before
public void setUp() throws Exception {
Project project = new Project("Project");
project.setId(1);
EasyMock.expect(projectRepositoryMock.findOne(1)).andReturn(project);
}
@After
public void tearDown() throws Exception {
}
@Test
public void getProjectById() throws Exception {
}
This is my project entity:
@Entity
@Table(name = "Project")
public class Project {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String projectName;
public Project(){
}
public Project(String projectName) {
this.projectNaam = projectName;
}
It also has the usual getters and setters.
My repository just extends the JpaRepository.
And this is my ProjectService class
@Service
public class ProjectService {
@Autowired
private ProjectRepository projectRepository;
public ProjectService(){
}
public Project getProjectById(Integer id){
return this.projectRepository.findOne(id);
}
public void saveProject(Project project){
this.projectRepository.save(project);
}
public void deleteProject(Integer id){
this.projectRepository.delete(id);
}
public List<Project> getAllProjects(){
return this.projectRepository.findAll();
}
public Project findProjectById(Integer id){
return this.projectRepository.findOne(id);
}
}
When I run my test class i get the error: java.lang.NullPointerException at com.example.testclusters.Service.ProjectServiceTest.setUp(ProjectServiceTest.java:25)
I think it has something to do with the Field id on the Project Entity is Generated. How is it possible to test this service in a good way with EasyMock?
The fact that the id
field is @GeneratedValue
has nothing to do with this.
My guess is that you have forgotten to instantiate and assign ProjectService
and ProjectReposistory
, thus giving a NullPointerException
. I haven't used EasyMock
, but from the documentation it seems that you are missing something like this:
@RunWith(EasyMockRunner.class)
public class ProjectServiceTest {
@Mock
private ProjectRepository projectRepositoryMock;
@TestSubject
private ProjectService service;
Also, providing a setter to your generated JPA id is dangerous. You NEVER want to set that id in production code. IMO it's better to remove the setter, and use reflection if you need to for testing purposes.