第一次一起使用EasyMock和Spring。
我有测试类:
@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 {
}
这是我的项目实体:
@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;
}
它也有通常的吸气剂和制定者。
我的存储库只是扩展了JpaRepository。
这是我的ProjectService类
@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);
}
}
当我运行我的测试类时,我得到错误:java.lang.NullPointerException 在com.example.testclusters.Service.ProjectServiceTest.setUp(ProjectServiceTest.java:25)
我认为它与Project Entity上的Field id有关。如何使用EasyMock以良好的方式测试此服务?
答案 0 :(得分:1)
id
字段为@GeneratedValue
这一事实与此无关。
我的猜测是你忘记了实例化并分配ProjectService
和ProjectReposistory
,从而给出NullPointerException
。我还没有使用EasyMock
,但是从文档中看来你似乎错过了这样的东西:
@RunWith(EasyMockRunner.class)
public class ProjectServiceTest {
@Mock
private ProjectRepository projectRepositoryMock;
@TestSubject
private ProjectService service;
此外,为生成的JPA ID提供setter是危险的。您永远不想在生产代码中设置该ID。 IMO最好删除setter,如果需要进行测试,请使用反射。
答案 1 :(得分:0)
我建议你阅读这个例子:
https://dzone.com/articles/easymock-tutorial-%E2%80%93-getting
#box2 {
margin: 50px auto 0 auto;
}
在测试中你可以创造你的期望。