1

我正在尝试使用 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...
    }
}

它为空的原因可能是什么?(我的课程/服务是 Spring bean)

4

1 回答 1

4

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

于 2013-02-04T20:37:04.320 回答