Spring EasyMock在调用mocked方法时变为null

时间:2017-09-20 13:01:47

标签: java spring easymock

第一次一起使用EasyMock和Spring。 我有测试类:

@RunWith(EasyMockRunner.class)
public class ProjectServiceTest {

    @Mock
    private ProjectRepository projectRepositoryMock;

    @TestSubject
    private ProjectService service new ProjectService();

    @Before
    public void setUp() throws Exception {
        Project project = new Project("Project");

        EasyMock.expect(projectRepositoryMock.findOne(1)).andReturn(project);
    }

    @After
    public void tearDown() throws Exception {
    }

    @Test
    public void getProjectById() throws Exception {
      System.out.println(this.service.getProjectById(1);
    }

这是我的项目实体:

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

我的测试失败了,这就是为什么我使用system.out.println来弄清楚发生了什么。它打印:null。

我不明白这一点。 @Mock和@TestSubject似乎很好,因为我想测试服务并模拟存储库。 而不是

System.out.println(this.service.getProjectById(1);

我试过

System.out.println(this.projectRepositoryMock.findOne(1));

但是这也会返回null。

1 个答案:

答案 0 :(得分:0)

您需要将模拟放入重播模式。尝试

@Before
public void setUp() throws Exception {
    Project project = new Project("Project");

    EasyMock.expect(projectRepositoryMock.findOne(1)).andReturn(project);
    EasyMock.replay(projectRepositoryMock);
}