I have a test where I do not need to run the SetUp
method (attributed with [SetUp]
) before running the test. I need the SetUp
method t
You can have the main SetUp
in a base class:
[SetUp]
public virtual void SetUp()
{
// Set up things here
}
...and then override it in the class where you have the tests that should not run the SetUp
code:
[SetUp]
public override void SetUp()
{
// By not calling base.SetUp() here, the base SetUp will not run
}
I don't believe you can do that, it would involve knowing what test was about to run which I don't think is possible.
I'd suggest you put it within a different [TestFixture]
Here is the code that I suggest for accomplishing what you want:
public const string SKIP_SETUP = "SkipSetup";
private static bool CheckForSkipSetup()
{
string category = string.Empty;
var categoryKeys = TestContext.CurrentContext.Test.Properties.Keys.ToList();
if (categoryKeys != null && categoryKeys.Any())
category = TestContext.CurrentContext.Test.Properties.Get(categoryKeys[0].ToString()) as string;
bool skipSetup = (!string.IsNullOrEmpty(category) && category.Equals(SKIP_SETUP)) ? true : false;
return skipSetup;
}
[SetUp]
public void Setup()
{
// Your setup code
}
[Test]
public void WithoutSetupTest()
{
// Code without setup
}
[Test]
[Category(SKIP_SETUP)]
public void CodeWithSetupTest()
{
// Code that require setup
}
You should create a new class for that test which has only the setup (or lack of setup) that it needs.
Alternatively, you could unfactor the setup code into a method that all the other tests call, but I don't recommend this approach.
You could also add a category and inspect the category list in your setup:
public const string SKIP_SETUP = "SkipSetup";
[SetUp]
public void Setup(){
if (!CheckForSkipSetup()){
// Do Setup stuff
}
}
private static bool CheckForSkipSetup() {
ArrayList categories = TestContext.CurrentContext.Test
.Properties["_CATEGORIES"] as ArrayList;
bool skipSetup = categories != null && categories.Contains( SKIP_SETUP );
return skipSetup ;
}
[Test]
[Category(SKIP_SETUP)]
public void SomeTest(){
// your test code
}
Here is the code that I suggest for accomplishing what you want.
public const string SKIP_SETUP = "SkipSetup";
Now add the following method:
private static bool CheckForSkipSetup()
{
var categories = TestContext.CurrentContext.Test?.Properties["Category"];
bool skipSetup = categories != null && categories.Contains("SkipSetup");
return skipSetup;
}
Now check the condition as follows:
[SetUp]
public async Task Dosomething()
{
if (!CheckForSkipSetup())
{
}
}
Use these in test cases as follows:
[Test]
[Category(SKIP_SETUP)]
public async Task Mywork()
{
}