简体   繁体   中英

Repeating test cases

My question is if it is ok to repeat the same test assertion or case for every scenario?

The scenario here is if I have a function, then this function can be simulated using different scenarios involving different sets of parameter combinations.

For example I have a function with 3 possible scenarios, in each scenario, 3 similar events happens everytime this scenario is simulated on this function.

When I write a test for scenario A then I will write 3 assertions to test the 3 events involve in this scenario. Is it ok to repeat the same pattern of assertions for other scenarios?

The assertions may not be necessarily the same but they have the same pattern.

I hope somebody will understand what I mean, I know this is too general because I want a general standpoint if this is really somewhat applicable on most cases.

It really is up to you to define what is adequate testing.

Some questions I ask myself:

Do the unit tests test all code paths? Do I cover typical cases? Do I cover corner cases? Do I cover exceptional cases(ie erronious input)?

I understand what you mean though, and I don't see anything wrong with using the same/similar test cases for multiple scenarios, so long as you cover the above questions.

Depending on what language/toolset/test framework you are using, parameterized tests might be the solution. They let you write a single test that gets called multiple times with different parameters, and are a great way of combining test cases that differ only in inputs or expected outputs.

Here's a simple example of how your tests might look using C# / NUnit:

[TestCase(true, false, 5)]
[TestCase(false, true, 99)]
public void Test_Foo_Bars(bool conditionA, bool conditionB, int expectedResult)
{
    var x = new MyClass(conditionA);
    var result = x.Foo(conditionB);
    result.ShouldBe(expectedResult);
}

This test gets executed twice; once with each set of parameters specified in the TestCase attribute.

The exact syntax and usage will of course depend on your toolset, but the basic idea is the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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