0

I'm new to unit testing and XUnit. I'm trying to write two test cases. One test is creating an item and the other test is deleting the item.

public class MyTests
{
    string id = string.Empty;

    [Fact]
    public void TestCreate()
    {
        id = MethodToCreateItem();
        Assert.NotNull(id);
    }

    [Fact]
    public void TestDelete()
    {
        bool success = MethodToDeleteItem(id);
        Assert.True(success);
    }
}

The TestCreate() runs fine. The id is set and the test is successful. However, the test TestDelete() doesn't work. When it gets to that test the value of id is empty.

How can I make it so that the second test has access to the value of id after the first test has ran?

James
  • 523
  • 1
  • 4
  • 20
  • What you describe there looks more like integration testing but I would suggest changing your approach to help isolate the subject under test in each test case. – Nkosi Mar 19 '20 at 01:46
  • 1
    As @Nkosi said unit tests are usually expected to be standalone independent methods. Some testing framework (including XUnit) allow you to define order of tests to run to implement what you trying to do here (I picked example as duplicate). Note that if you are just learning unit testing you should not be making tests dependent on each other - rewrite your test cases so each test single fact and restores environment to default state. – Alexei Levenkov Mar 19 '20 at 03:13
  • @AlexeiLevenkov the second test case is only loosely dependent on the first. The problem is that I need an ID of an item to delete and I can only do that if I first create the item to get an ID of an item that can be deleted. – James Mar 20 '20 at 01:19

0 Answers0