在相同的测试用例或单独的测试用例中测试默认值和setter [英] Test default value and setter in same test-case or separate test cases

查看:142
本文介绍了在相同的测试用例或单独的测试用例中测试默认值和setter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您是否建议在@Test方法中进行任何测试用例分组,或者每个测试方案都有一个@Test方法?例如,假设有不同的方法在应用程序中设置上下文。

Would you recommend doing any grouping of test cases within @Test methods, or have one @Test method per test scenario? For example, let's suppose that there are different ways to set the context in an application.

以下想法是否可以接受?

Is the following idea acceptable?

@Test
public void testContextSetting() {
    // Test default setting
    assert(...)

    // Test setting a context variable
    assert(...)

    ...
}

或者,您是否愿意建议这样做,让每种方法尽可能原子化:

Or, would you rather suggest having it like this, having each method as atomic as possible:

@Test
public void textDefaultSetting() {
    // Test default setting
    assert(...)
}

@Test
public void testSettingContextVar() {
    // Test setting a context variable
    assert(...)

    ...
}

任何反馈都将不胜感激。

Any feedback would be appreciated.

推荐答案

我更喜欢每种方法都有一个测试用例。

I prefer having one test case per method.

首先,更容易看出是什么情况正在测试它们是否被分解为方法而不是寻找代码中嵌入的注释。大多数IDE都会给你一个方法摘要,所以不要说我测试过edgecase XYZ吗?然后寻找评论,或者寻找设置该边框的代码,你只需要找到名为 setupContextEdgeCaseXYZ()的方法。

First it is easier to see what cases are being tested if they are split into methods as opposed to looking for comments embedded in the code. Most IDEs will give you a summary of methods, so instead of saying "did I test edgecase XYZ?" and then hunting for a comment, or looking for the code that sets up that edgecase, you just look for the method named setupContextEdgeCaseXYZ().

第二个原因是,如果你有多个案件,一个可能会失败,然后其他人永远不会执行。

A second reason is if you have multiple cases together one may fail and then the others never execute.

 testDefaultCase()
 testInvalidInput()
 testEdgeCase1()
 testEdgeCase2()

使用这种结构可以更容易地确定输入检查是错误的并且边缘情况2被不正确地处理,但是其他情况都是正常的(并且您可能发现两个失败的情况是相关的并且问题被诊断得更快)。

With this structure it would be easier to determine that the input checking is bad and edge case 2 is handled improperly, but the others are OK (and you may find out that two failing cases are related and the problem is diagnosed faster).

第三个原因是你可能会意外地保留先前测试集中的值,这些值会以不显眼的方式使后一测试无效。一个简单的例子:

A third reason is you may accidentally leave values from a previous test set that invalidates a latter test in a inconspicuous way. A simple example:

@Test
public void testMyMethod() {
  //test default
  String test = Foo.bar(null);
  assertEquals("foo", test);

  //test case 1
  Foo.bar(aValue);
  //Oops forgot to set value above, this passes regardless of 
  //what the above call does
  assertEquals("foo", test);
}

通过区分案件你可以避免上述错误,因为这会导致错误编译错误或警告。

By breaking cases apart you can avoid mistakes as above as that would turn into a compile error or warning.

这篇关于在相同的测试用例或单独的测试用例中测试默认值和setter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆