首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在JUnit测试中使用带有依赖注入的模拟类

在JUnit测试中使用带有依赖注入的模拟类
EN

Stack Overflow用户
提问于 2013-04-11 15:48:42
回答 1查看 4.9K关注 0票数 0

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

代码语言:javascript
复制
package info;

import org.springframework.stereotype.Service;

public interface Student 
{
    public String getStudentID();
}

`

代码语言:javascript
复制
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";
    }
}

然后我就有了一个要注入那个类的服务。

代码语言:javascript
复制
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中的方法单步执行。注入确实可以工作,但为了测试,我想使用一个类来模拟结果。任何帮助都将不胜感激。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-04-11 15:58:05

在我看来,单元测试中的自动装配是一个信号,表明它是一个集成测试而不是单元测试,所以我更喜欢像你所描述的那样做我自己的“连接”。它可能需要您对代码进行一些重构,但这应该不是问题。在本例中,我将向get的Student实现的InfoService添加一个构造函数。如果您愿意,也可以将此构造函数设为@Autowired,并从student字段中删除@Autowired。Spring将仍然能够自动生成它,而且它也更具可测试性。

代码语言:javascript
复制
@Service
public class InfoService {
    Student student;

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

}

那么在你的测试中在你的服务之间传递mock将是微不足道的:

代码语言:javascript
复制
@Test
public void myTest() {
    Student mockStudent = mock(Student.class);
    InfoService service = new InfoService(mockStudent);
}
票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15943346

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档