Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why xunit not allow test a method with parameters?

Tags:

xunit

I am learning to use unit test, i create a project, add xunit reference. And following codes:

namespace UnitTestProject
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        [Fact]
        private void test(int number1, string number2)
        {

            int result = number1 + Convert.ToInt32(number2);
            Assert.IsType(Type.GetType("Int32"), result);
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

When i run the test using xunit gui tool, it said:

UnitTestProject.Form1.test : System.InvalidOperationException : Fact method UnitTestProject.Form1.test cannot have parameters Stack Trace: 於 Xunit.Sdk.FactCommand.Execute(Object testClass)
Xunit.Sdk.FixtureCommand.Execute(Object testClass)
Xunit.Sdk.BeforeAfterCommand.Execute(Object testClass)
Xunit.Sdk.LifetimeCommand.Execute(Object testClass)
Xunit.Sdk.ExceptionAndOutputCaptureCommand.Execute(Object testClass)

So, how can i test the method/function with parameters?

like image 972
Cheung Avatar asked Nov 17 '11 06:11

Cheung


People also ask

Which of the following attributes are eliminated in xUnit?

Thereby, the xUnit test eliminates the risk of test method dependencies.

What is difference between Fact and Theory in xUnit?

Fact vs Theory Tests The primary difference between fact and theory tests in xUnit is whether the test has any parameters. Theory tests take multiple different inputs and hold true for a particular set of data, whereas a Fact is always true, and tests invariant conditions.

Is xUnit a test runner?

The MSBuild runner in xUnit.net v2 is capable of running unit tests from both xUnit.net v1 and v2. It can run multiple assemblies at the same time, and build file options can be used to configuration the parallelism options used when running the tests.


1 Answers

Also you can use [Theory] instead of [Fact]. It will allow you to create test methods with different parameters. E.g.

[Theory]
[InlineData(1, "22")]
[InlineData(-1, "23")]
[InlineData(0, "-25")]
public void test(int number1, string number2)
{
    int result = number1 + Convert.ToInt32(number2);
    Assert.IsType(Type.GetType("Int32"), result);
}

p.s. With xUnit it would be better to make test methods public.

like image 142
Alina Avatar answered Sep 27 '22 22:09

Alina