c# unit test
Items to be tested:
namespace LambdaTest
{
class Program
{
static void Main(string[] args)
{
var fan = new DeskFan(new PowerSupply());
Console.WriteLine(fan.Work());
}
}
public interface IPowerSupply
{
int GetPower();
}
public class PowerSupply : IPowerSupply
{
public int GetPower()
{
return 170;
}
}
public class DeskFan
{
private IPowerSupply _powerSupply;
public DeskFan(IPowerSupply powerSupply)
{
_powerSupply = powerSupply;
}
public string Work()
{
int power = _powerSupply.GetPower();
if (power <= 120)
{
return "Low Voltage";
}
else if (power >= 200)
{
return "Over Voltage";
}
else
{
return "Fine Power";
}
}
}
}
Unit test steps
Right-click Solution, select Add, new project:
select Unit Test or xUnit Test:
fill in the project name, click Create:
add a reference
to the project to be tested: select the project:
Write unit test code:
namespace InterfaceExample_UnitTest
{
[TestClass]
public class TestExample
{
[TestMethod]
public void PowerLower()
{
var fan = new DeskFan(new PowerLowerExample());
var expected = "Low Voltage";
var actual = fan.Work();
Assert.AreEqual(expected, actual);
}
[TestMethod]
public void PowerHigher()
{
var fan = new DeskFan(new PowerHigherExample());
var expected = "Over Voltage";
var actual = fan.Work();
Assert.AreEqual(expected, actual);
}
class PowerLowerExample : IPowerSupply
{
int IPowerSupply.GetPower()
{
return 80;
}
}
class PowerHigherExample : IPowerSupply
{
int IPowerSupply.GetPower()
{
return 240;
}
}
}
}
Open Test Explore, view,
right-click case, Run, and view the running results: The
above solution structure:
Use mork to simplify unit test writing
Mork can omit tedious interface definitions like the following:
The process is recorded as follows:
Right-click the project, select Manage NuGet Packages
and search for Moq in Browse:
select, click Install:
select OK:
installation is complete:
return to the test project, modify the code: