【发布时间】:2013-02-04 20:26:03
【问题描述】:
我正在尝试使用 Mockito 模拟一个具体的类。但是,它在被测服务中仍然为 null。
我的具体课程和服务:
//My Concrete Class
@Component("supporter")
public class Supporter
{
@Autowired
private IDriver driver;
public int someMethod(int){...}
...
}
//Service Class that uses this abstract class
public class Service implements IService
{
private ExceptionHandler exceptionHandler;
@Autowired
public void setExceptionHandler(ExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
private Supporter supporter;
@Autowired
public void setSupporter(Supporter supporter) {
this.supporter = supporter;
}
public int hookItem(int arg)
{
...
//supporter is always null while mock testing <----
int count = supporter.someMethod(arg);
...
return count;
}
}
我的测试代码:
public class ServiceTest extends AbstractTestMockito
{
...
IService service = null;
@Mock
private ExceptionHandler exceptionHandler;
@BeforeMethod
public void setup() {
service = new Service();
}
@Test(enabled=true)
public void shouldDoSomething()
{
Supporter supporter = Mockito.mock(Supporter.class);
given(supporter.someMethod(1)).willReturn(new Integer(10));
final int response = service.hookItem(1);
//Assert...
}
}
它为空的原因可能是什么? (我的类/服务是 Spring bean)
【问题讨论】:
-
service变量从何而来?还有null是哪一个? -
添加了“服务”创建(在@BeforeMethod 中)。 'supporter' 在 Service 类中为空(显示在评论中)
-
你打电话给 Mockito.initMocks(this) 了吗?
-
是的,它是在 AbstractTestMockito 类中作为 @BeforeMethod 完成的
标签: java spring mocking mockito