Ara*_*ind 2 .net c# unit-testing moq
我有小样本工厂模式实现的下方,并想知道如果有人可以帮我写正确的起订量的单元测试用例,最大代码覆盖率:
public class TestClass
{
private readonly IService service;
public TestClass(Iservice service)
{
this.service = service;
}
public void Method(string test)
{
service = TestMethod(test);
service.somemethod();
}
private IService TestMethod(string test)
{
if(test == 'A')
service = new A();
if(test == 'B')
service = new B();
return service;
}
}
Run Code Online (Sandbox Code Playgroud)
我正在寻找测试TestClass的一些帮助,更重要的是我发送Mock时的TestMethod,例如我的测试方法如下:
[TestMethod]
public void TestCaseA()
{
Mock<IService> serviceMock = new Mock<Iservice>(MockBehaviour.strict);
TestClass tClass = new TestClass(serviceMock.Object);
// The Question is, what is best approach to test this scenario ?
// If i go with below approach, new A() will override serviceMock
// which i am passing through constructor.
var target = tClass.Method("A");
}
Run Code Online (Sandbox Code Playgroud)
你不会嘲笑TestClass,因为那是你正在测试的.
为此,您需要为其创建只读属性service.
public IService Service { get; private set; }
Run Code Online (Sandbox Code Playgroud)
您需要测试构造函数的方式并Method修改实例的状态(在本例中Service)TestClass.
您的测试将类似于用于测试下面Method的B测试案例:
[TestMethod]
public void TestSomeMethod()
{
// Arrange/Act
var target = new TestClass((new Mock<IService>()).Object);
target.Method("B");
// Assert
Assert.IsInstanceOfType(target.Service, typeof(B));
}
Run Code Online (Sandbox Code Playgroud)
为测试测试用例的构造函数,您的测试看起来类似于以下内容A:
[TestMethod()]
public void TestCasesA()
{
// Arrange/Act
var target = new TestClass("A");
// Assert
Assert.IsInstanceOfType(target.service, typeof(A));
}
Run Code Online (Sandbox Code Playgroud)
我建议只使用构造函数方法来注入你的IService.这允许您拥有一个不可变对象,这将减少您的应用程序的状态.
| 归档时间: |
|
| 查看次数: |
5987 次 |
| 最近记录: |