在JUnit测试中使用Mock类和依赖注入

Jam*_*ond 0 junit spring dependency-injection mockito

我有一个基本接口,另一个类正在实现.

package info;

import org.springframework.stereotype.Service;

public interface Student 
{
    public String getStudentID();
}
Run Code Online (Sandbox Code Playgroud)

`

package info;

import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

@Service
public class StudentImpl implements Student
{
    @Override
    public String getStudentID() 
    {
        return "Unimplemented";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有一个服务来注入该类

package info;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Service
public class InfoService {

    @Autowired
    Student student;

    public String runProg()
    {
            return student.getStudentID();
    }
}
Run Code Online (Sandbox Code Playgroud)

我想知道的是,如何设置JUnit测试,以便Student接口的Mock类使用stubbed方法而不是StudentImpl中的方法.注入确实有效但我想使用amock类来模拟结果而不是为了测试.任何帮助将不胜感激.

Nil*_*lsH 6

在我看来,单元测试中的自动装配是一个标志,它是一个集成测试,而不是单元测试,所以我更喜欢自己做"布线",正如你所描述的那样.它可能需要您对代码进行一些重构,但这不应该是一个问题.在你的情况下,我会添加一个构造函数来InfoService获得一个Student实现.如果您愿意,您也可以创建此构造函数@Autowired,并@Autowiredstudent字段中删除它.然后Spring仍然能够自动装配它,而且它也更容易测试.

@Service
public class InfoService {
    Student student;

    @Autowired
    public InfoService(Student student) {
        this.student = student;
    }

}
Run Code Online (Sandbox Code Playgroud)

那么在测试中将服务之间的模拟传递起来是微不足道的:

@Test
public void myTest() {
    Student mockStudent = mock(Student.class);
    InfoService service = new InfoService(mockStudent);
}
Run Code Online (Sandbox Code Playgroud)