Nunit setup / teardown not working?

Ok, I have a strange problem. I am testing usercontrol and have code like this:

[TestFixture]
public myTestClass : UserControl
{
    MyControl m_Control;

    [Test]
    public void TestMyControl()
    {
        m_Control = new MyControl();
        this.Controls.Add(m_Control);

        Assert.That(/*SomethingOrOther*/)
    }
}

This works fine, but when I change it to:

[TestFixture]
public myTestClass : UserControl
{
    MyControl m_Control;

    [Setup]
    public void Setup()
    {
        m_Control = new MyControl();
        this.Controls.Add(m_Control);
    }

    [TearDown]
    public void TearDown()
    {
        this.Controls.Clear();
    }

    [Test]
    public void TestMyControl()
    {
        Assert.That(/*SomethingOrOther*/);
    }
}

I get a reference to an object not set to an instance of the object. I even go out to the console to make sure the installation / shutdown works at the right time, and they were ... but still, this is not a new user control.

edit> Exact code:

[TestFixture]
public class MoneyBoxTests : UserControl
{
    private MoneyBox m_MoneyBox;
    private TextBox m_TextBox;

    #region "Setup/TearDown"
    [SetUp]
    public void Setup()
    {
        MoneyBox m_MoneyBox = new MoneyBox();
        TextBox m_TextBox = new TextBox();

        this.Controls.Add(m_MoneyBox);
        this.Controls.Add(m_TextBox);
    }

    [TearDown]
    public void TearDown()
    {
        this.Controls.Clear();
    }
    #endregion

    [Test]
    public void AmountConvertsToDollarsOnLeave()
    {
        m_MoneyBox.Focus();
        m_MoneyBox.Text = "100";
        m_TextBox.Focus();

        Assert.That(m_MoneyBox.Text, Is.EqualTo("$100.00"), "Text isn't $100.00");
    }

    [Test]
    public void AmountStaysANumberAfterConvertToDollars()
    {
        m_MoneyBox.Focus();
        m_MoneyBox.Text = "100";
        m_TextBox.Focus();

        Assert.That(m_MoneyBox.Amount, Is.EqualTo(100), "Amount isn't 100");
    }
}

I get exception (s) in the corresponding calls to m_MoneyBox.Focus ().

Solved - see Joseph's comments

+3
source share
3 answers

, , TextBox MyControl. , . , .

, , [ ], [setup called], [test called], [tear down called]. - .

, Controls myTestClass , , , - MyControl.

edit > TextBox unit test, . MoneyBox - , Focus? .

+3

, , - ?

(IME) UserControl . , , NUnit Dispose ... ? "" ?

+3

, . ( ) , 2 MoneyBox 2 TextBox. , Setup out_of_scope .

:

m_MoneyBox = new MoneyBox(); //GOOD
m_TextBox = new TextBox();  //GOOD

MoneyBox m_MoneyBox = new MoneyBox();  //BAD
TextBox m_TextBox = new TextBox();  //BAD

,

+2
source

Source: https://habr.com/ru/post/1703749/


All Articles