【问题标题】:Using Mock class with dependency injection in a JUnit test在 JUnit 测试中使用具有依赖注入的 Mock 类
【发布时间】:2013-04-11 07:48:42
【问题描述】:

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

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 测试,以便 Student 接口的 Mock 类使用存根方法而不是 StudentImpl 中的方法介入。注入确实有效,但我想使用 amock 类来模拟结果,而不是为了测试。任何帮助将不胜感激。

【问题讨论】:

    标签: spring junit dependency-injection mockito


    【解决方案1】:

    在我看来,单元测试中的自动装配表明它是集成测试而不是单元测试,所以我更喜欢按照您的描述进行自己的“装配”。它可能需要您对代码进行一些重构,但这应该不是问题。在您的情况下,我会向 InfoService 添加一个构造函数,它是一个 Student 实现。如果您愿意,也可以将此构造函数设为@Autowired,并从student 字段中删除@Autowired。然后 Spring 仍然可以自动装配它,而且它也更易于测试。

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

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

    @Test
    public void myTest() {
        Student mockStudent = mock(Student.class);
        InfoService service = new InfoService(mockStudent);
    }
    

    【讨论】:

    • 有什么特别的东西必须放在 JUnit 中才能使它工作吗?意图是使用when(fakeStudent.getStudentId()).thenReturn("Some Value");
    • 不,在您的测试中,您只需创建您的模拟,然后自己“连接”它。我在答案中添加了一个简单的示例。
    • 似乎仍然无法正常工作。我仍然从StudentImpl 获取字符串。
    • 您可能必须在没有标准 JUnit 运行器的情况下运行测试。不是 Spring 提供的那种。它将在您的测试中禁用自动装配。
    • 它确实有效。每当我初始化InfoService 时,我一直在分配ApplicationContextBeanFactory。一旦我从测试中删除它们,它就开始工作了。
    猜你喜欢
    • 1970-01-01
    • 2017-02-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    • 2018-12-27
    • 1970-01-01
    • 2018-12-10
    相关资源
    最近更新 更多