Initialize an object for testing in SetUp or during a test method?

I was wondering if the object to be tested should be a field and thus configured during the method SetUp(e.g. JUnit, nUnit, MS Test, ...).

Consider the following examples (this is C♯ with MsTest, but the idea should be similar for any other language and testing framework):

public class SomeStuff
{
    public string Value { get; private set; }

    public SomeStuff(string value)
    {
        this.Value = value;
    }
}


[TestClass]
public class SomeStuffTestWithSetUp
{
    private string value;
    private SomeStuff someStuff;

    [TestInitialize]
    public void MyTestInitialize()
    {
        this.value = Guid.NewGuid().ToString();
        this.someStuff = new SomeStuff(this.value);
    }

    [TestCleanup]
    public void MyTestCleanup()
    {
        this.someStuff = null;
        this.value = string.Empty;
    }

    [TestMethod]
    public void TestGetValue()
    {
        Assert.AreEqual(this.value, this.someStuff.Value);
    }
}

[TestClass]
public class SomeStuffTestWithoutSetup
{
    [TestMethod]
    public void TestGetValue()
    {
        string value = Guid.NewGuid().ToString();
        SomeStuff someStuff = new SomeStuff(value);
        Assert.AreEqual(value, someStuff.Value);
    }
}

Of course, with just one test method, the first example is too long, but with a lot of test methods, this can be safe, pretty redundant code.

What are the pros and cons of each approach? Are there any "best practices"?

+5
source share
6 answers

, . , .

BDD. , . [] , , .

, , :

OrderFulfillmentServiceTests.cs

  • with_an_order_from_a_new_customer

    • ,

. "with_an..." , - . ( ), , , .

+8

.

.

, SetUp ( ), , . /.

+1

jUnit , Test Classes , . , , , .

+1

Setup Teardown , , .

  • Setup Teardown, , , (), , .
  • Setup Teardown, , , , , TestMethod.

, , , , ( ) Setup Teardown, - 10- , .

, TestMethod, .

0

, , - - TearDown SetUp "" ( ), - , . " ". InstantiateClass(). ( ), .

[Test]
public void TestSomething()
{
    _myVar = "value";
    InstantiateClass();
    RunTheClass();
    Assert.IsTrue(this, that);
}
0

In practice, I find that the setup methods make it difficult to reason about the failure of the test and should scroll somewhere at the top of the file (which can be very large) to find out what the co-author violated (not easily with a mockery) and there is no link to the link for Navigating in your IDE In short, you are losing spatial locality.

Static helper methods are shown in more detail to employees, and you avoid fields that unnecessarily expand the scope of variables.

0
source

All Articles