【问题标题】:Mocking a concrete class - It's always null模拟一个具体的类 - 它总是空的
【发布时间】: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


【解决方案1】:

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

【讨论】:

  • 就是这样。谢谢你。但是,我有一个后续问题。我更新了我的问题 - 我也有一个接口 ExceptionHandler。为什么我不需要显式设置它(因为它不是空的,在服务内部)? Mockito 是否能够自动注入接口模拟?
  • 是的,当我阅读您的示例和 cmets 时,我了解到您正在使用 @Mock 注释和 Mockito.initMocks(this); 您可以在 @ 的 JavaDoc 中阅读有关该(和其他功能)的更多信息987654321@班级。此外,大约一年前,我就这个主题写了一个blog post,你可能会觉得有趣。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2012-03-02
  • 2016-02-14
  • 1970-01-01
  • 1970-01-01
  • 2011-02-08
相关资源
最近更新 更多