简体   繁体   English

在Java中模拟多级数组以进行单元测试

[英]Mock multiple level arrays in java for unit testing

Hypothetically I have 假设我有

class Box{
   Item[] items;
}

class Item{
   Toy[] toys;
}

class Toy{
   Color[] colors;
}

The method is to test if the Box has green color toy; 方法是测试盒子是否有绿色玩具;

public bool testHasColor(Box){
   //There will be code here that
   //Streams over each type till we get to color
   // Final point is
   if(color==Color.GREEN){
    return true;
   }
}

BoxText.class BoxText.class

public void testBoxHasColorGreenMethod(){
    // Need mocking here
}

What the best way to mock this Box class for the test case? 在测试用例中模拟Box类的最佳方法是什么?

Thank you 谢谢

You don't need to mock any Java APIs. 您不需要模拟任何Java API。 You just need to "mock" some data which is usually not called "mocking" - just testing. 您只需要“模拟”一些通常不称为“模拟”的数据-只是测试即可。 So you would just create a test instance of Box and test if your method produces the expected outcome. 因此,您只需创建Box的测试实例,然后测试您的方法是否产生了预期的结果。

    Box box = new Box();
    Item item = new Item();
    Toy toy = new Toy();

    box.items = new Item[] {item};
    item.toys = new Toy[] {toy};
    toy.colors = new Color[] {Color.RED, Color.GREEN};

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

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