我有一个基本的接口,另一个类正在实现。
package info;
import org.springframework.stereotype.Service;
public interface Student
{
public String getStudentID();
}`
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";
}
}然后我就有了一个要注入那个类的服务。
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();
}
}我想知道的是,我如何设置一个JUnit测试,以便学生接口的模拟类使用存根方法而不是StudentImpl中的方法单步执行。注入确实可以工作,但为了测试,我想使用一个类来模拟结果。任何帮助都将不胜感激。
发布于 2013-04-11 15:58:05
在我看来,单元测试中的自动装配是一个信号,表明它是一个集成测试而不是单元测试,所以我更喜欢像你所描述的那样做我自己的“连接”。它可能需要您对代码进行一些重构,但这应该不是问题。在本例中,我将向get的Student实现的InfoService添加一个构造函数。如果您愿意,也可以将此构造函数设为@Autowired,并从student字段中删除@Autowired。Spring将仍然能够自动生成它,而且它也更具可测试性。
@Service
public class InfoService {
Student student;
@Autowired
public InfoService(Student student) {
this.student = student;
}
}那么在你的测试中在你的服务之间传递mock将是微不足道的:
@Test
public void myTest() {
Student mockStudent = mock(Student.class);
InfoService service = new InfoService(mockStudent);
}https://stackoverflow.com/questions/15943346
复制相似问题