简体   繁体   English

如何用Java对添加到集合中的单元进行单元测试?

[英]How do I unit test adding to a collection in Java?

I'm still coming to terms with unit testing certain things and I have a question about my JUnit test for a relatively simple class: 我仍然对单元测试某些事情还不满意,对于一个相对简单的类,我对我的JUnit测试有疑问:

public class Kite {
    private List<String> strings = new ArrayList<String>();

    public void addString(String string) { //... }
    public void removeString(String string) { //... }
    public List<String> getStrings() { //... }
    public int getNumStrings() { //... }
}

In this case I would like to test all four methods. 在这种情况下,我想测试所有四种方法。 However the tests, now that I've written them, are all very similar. 但是,既然我已经编写了测试,它们都非常相似。 They (excluding the remove) all follow the basic structure of add a String to a Kite and then checking the number of Strings in the Kite object. 它们(不包括删除)都遵循将字符串添加到Kite,然后检查Kite对象中的字符串数的基本结构。

Is there a better way to test these "CRUD" types of methods? 有没有更好的方法来测试这些“ CRUD”类型的方法?

Do I need to test them? 我需要测试吗?

It's better to be more specific in your testing. 最好在测试中更具体。 For addString(), you want to test that: 对于addString(),您想测试一下:

  1. The string you added is present in the collection. 您添加的字符串出现在集合中。

  2. No other strings were added to the collection as a side effect. 没有其他字符串作为副作用添加到集合中。

  3. If you pass null to addString(), an IllegalArgumentException (or whatever the behavior should be) is thrown 如果将null传递给addString(),则抛出IllegalArgumentException(或其他行为)

  4. If you pass the same string in twice, the behavior is what you want (could be an IllegalArgumentException, could be a no-op) 如果您两次传入相同的字符串,则行为就是您想要的(可能是IllegalArgumentException,可能是无操作)

get the idea? 有主意吗? You want to add tests for edge cases, as well as the normal behavior (sometimes called the "happy path"). 您要添加针对极端情况以及正常行为(有时称为“快乐之路”)的测试。 Think about your tests in terms of possible inputs, possible outputs, and code paths that can be taken. 根据可能的输入,可能的输出和可以采用的代码路径来考虑您的测试。

I would think about writing one test that models a transaction: 我会考虑编写一个对交易进行建模的测试:

  1. Check the pre-condition. 检查前提条件。
  2. Perform add operation. 执行添加操作。
  3. Check post-condition. 检查后置条件。
  4. Rollback add operation with remove. 使用remove进行回滚添加操作。
  5. Make sure that Kite is in original state. 确保风筝处于原始状态。

All those methods will be tested that way. 所有这些方法都将以这种方式进行测试。

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

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