EasyMock 和 Spring 自动装配

EasyMock And Spring Autowired

第一次同时使用 EasyMock 和 Spring。

我有测试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 {

    }

这是我的项目实体:

@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;
    }

它还有常用的 getter 和 setter。

我的存储库只是扩展了 JpaRepository。

这是我的 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);
    }
}

当我 运行 我的测试 class 我得到错误: java.lang.NullPointerException 在 com.example.testclusters.Service.ProjectServiceTest.setUp(ProjectServiceTest.java:25)

我认为这与Project Entity is Generated上的Field id有关。如何使用 EasyMock 以良好的方式测试此服务?

id 字段是 @GeneratedValue 的事实与此无关。

我的猜测是您忘记了实例化和分配 ProjectServiceProjectReposistory,因此给出了 NullPointerException。我没有使用过 EasyMock,但是从文档看来你缺少这样的东西:

@RunWith(EasyMockRunner.class)
public class ProjectServiceTest {

    @Mock
    private ProjectRepository projectRepositoryMock;

    @TestSubject
    private ProjectService service; 

此外,为您生成的 JPA id 提供 setter 是危险的。您永远不想在生产代码中设置该 ID。 IMO 最好删除 setter,并在需要时使用反射进行测试。

我建议你阅读这个例子:

https://dzone.com/articles/easymock-tutorial-%E2%80%93-getting

@Before
public void setUp() throws Exception {
    //you need to initialize the objects and Mock
    Project project = new Project("Project");
    project.setId(1);
    EasyMock.createMock(ProjectRepository.class);
}

在测试中你可以创造你的期望。