繁体   English   中英

问题使用Mockito的方法

[英]Issue Using Mockito's When Method

我正努力自学Mockito。

考虑下面的方法hasInventory() ,它不应该以我的思维方式运行,而是设置为返回truefalse,因为我松鼠笼罩我的测试。 Class Warehouse是我的“模仿依赖”。

public class Warehouse implements IWarehouse
{
  private Map< String, Integer >    inventory;

  public Warehouse()
  {
    this.inventory = new HashMap< String, Integer >();
  }

  public final boolean hasInventory( String itemname, int quantity )
      throws InventoryDoesNotExistException
  {
    if( inventory == null )
      throw new InventoryDoesNotExistException();

    if( !inventory.containsKey( itemname ) )
      return false;

    int current = ( inventory.containsKey( itemname ) ) ? inventory.get( itemname ) : 0;

    return( current >= quantity );
  }
  ...

在JUnit测试代码中,第一个when()抛出异常,因为它实际上解释了方法调用(执行它),而库存为nil(见上文),抛出了InventoryDoesNotExistException mocked依赖类中还有其他方法,如add()remove()

@RunWith( MockitoJUnitRunner.class )
public class OrderInteractionTest
{
  private static final String TALISKER = "Talisker";
  private Order   systemUnderTest  = null;

  @Mock
  private Warehouse   mockedDependency = null;

  @Before
  public void init()
  {
    //MockitoAnnotations.initMocks( this );
    //mockedDependency = mock( Warehouse.class );
    this.systemUnderTest  = new Order( TALISKER, 50 );
  }

  @Test  
  public void testFillingRemovesInventoryIfInStock()  
  {  
    try  
    {  
      doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).add( anyString(), anyInt() );  
      doNothing().doThrow( new RuntimeException() ).when( mockedDependency ).remove( anyString(), anyInt() );  
      when( mockedDependency.hasInventory( anyString(), anyInt() ) ).thenReturn( true );  
      when( mockedDependency.getInventory( anyString() ) ).thenReturn( 50 );

据我了解,由()方法 ,我问精确的Mockito不叫hasInventory(),但只是为我测试类(“systemUnderTest”)返回true,而不是在调用时。 任何人都可以帮助我克服这一点(或者对我的大脑有所了解)吗?

我正在连接mockito-all-1.8.5.jar和JUnit 4。

非常感谢所有阅读此内容的人。

拉斯

Mockito无法模拟final类或方法。 尝试从hasInventory方法中删除final修饰符。 或者更好的是,不要模拟Warehouse类,而是模拟IWarehouse接口,其方法不能是final ,并且可能定义Order使用的接口。

一般来说,最好是模拟接口,但它不是强制性的。

在Mockito FAQ中简要提到了无法模拟final类或方法,这是由于用于创建模拟的运行时类生成技术。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM