简体   繁体   English

void方法的单元测试应该如何?

[英]How the unit test for the void method should look like?

I wrote the program that simulates the basket in the shop. 我编写了模拟商店中购物篮的程序。 The user is able to add and remove items from the basket. 用户能够在购物篮中添加和删除物品。 Now, I am wondering, how the unit test for my (void) methods should look like. 现在,我想知道(无效)方法的单元测试应该是什么样子。 I am using the JUnit 4. 我正在使用JUnit 4。

I have tried to change my addItem method to return the boolean type, instead of returning nothing. 我试图更改我的addItem方法以返回布尔类型,而不是不返回任何内容。 With that I am able to write simple Assert.assertTrue(basket.add...) . 这样我就可以编写简单的Assert.assertTrue(basket.add...) But I do not know, how the unit test for the void method should be written. 但是我不知道,应该如何编写void方法的单元测试。

public boolean addItem(Item item) {
    if (orderedItems.containsKey(item)) {
        Integer currItemCount = orderedItems.get(item);
        orderedItems.replace(item, currItemCount, currItemCount + 1);
        return true;
    } else {
        orderedItems.put(item, 1);
        return true;
    }
}

public void addItem(Item item) {
    if (orderedItems.containsKey(item)) {
        Integer currItemCount = orderedItems.get(item);
        orderedItems.replace(item, currItemCount, currItemCount + 1);
    } else {
        orderedItems.put(item, 1);
    }
}

Note that the boolean is helpless in your first version since it always return true . 请注意,布尔值在您的第一个版本中是无助的,因为它总是返回true Besides, adding a boolean will really not help you to unit test your code since that is too shallow. 此外,添加布尔值实际上并不能帮助您对代码进行单元测试,因为这太浅了。 So you should stick to your original idea (without boolean). 因此,您应该坚持最初的想法(不带布尔值)。

About your question : yes the addItem() method does not return anything but if you can add items in the basket, you very probably want to read them too. 关于您的问题:是的, addItem()方法不会返回任何内容,但是如果您可以在购物篮中添加项目,则您很可能也希望阅读它们。
The simplest way of testing add() is relying on a get()/find() method. 测试add()的最简单方法是依靠get()/find()方法。
And reversely. 相反。

You could write something like that for a test with a item not present in the basket : 您可以编写类似这样的内容来测试篮子中没有的物品:

@Test
public void addItem_given_item_not_present_then_getAll_retrieves_it() {
   basket.addItem(new Item("foo"));
   Map<Item, Integer> items = basket.getAll();
   // assert items contains 1 element with 1 occurrence and with the foo name
}

And you should of course write other test scenarios. 当然,您应该编写其他测试方案。

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

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