嘲弄一个具体的类 - 它总是空的

时间:2013-02-04 20:26:03

标签: java spring mocking mockito

我正在尝试使用Mockito模拟一个具体的类。但是,它在被测服务中仍为空。

我的具体课程和服务:

//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...
    }
}

它可能是什么原因? (我的课程/服务是春豆)

1 个答案:

答案 0 :(得分:4)

查看测试类,您似乎没有将模拟的Supporter实例注入service实例,例如尝试在致电service.setSupporter(supporter);之前添加service.hookItem(1)