2013-04-11 124 views
0

我有一个基本的接口,其他类正在实现。在JUnit测试中使用Mock类与依赖注入

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类使用stubbed方法,而不是StudentImpl中的方法。注射确实有效,但我想使用amock类来模拟结果,而不是为了测试。任何帮助将不胜感激。

回答

6

在我看来,单元测试中的自动装配是一个标志,它是一个集成测试,而不是单元测试,所以我更愿意按照您的描述进行自己的“连线”。它可能需要你对代码进行一些重构,但它不应该是一个问题。在你的情况下,我会添加一个构造函数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); 
} 
+0

有什么特别的你必须在JUnit的地方,为了这个工作?目的是使用'when(fakeStudent.getStudentId())。然后返回(“Some Value”);' – 2013-04-11 08:05:30

+0

不,在你的测试中,你只需创建你的mock然后自己“连接”它。我给答案增加了一个简单的例子。 – NilsH 2013-04-11 08:06:33

+0

仍似乎没有工作。我仍然从'StudentImpl'获取字符串。 – 2013-04-11 08:14:03