假设以下场景:我有一个PhoneController使用Phone类的类。Phone是一个继承自抽象类Device并实现IPhone接口的类。为了测试,PhoneController我想模拟Phone类,但我不知道如何使用 NSubstitute 来完成它,因为Phone类继承了抽象类,并且还实现了接口。
示例代码:
public abstract class Device
{
protected string Address { get; set; }
}
public interface IPhone
{
void MakeCall();
}
public class Phone : Device, IPhone
{
public void MakeCall()
{
throw new NotImplementedException();
}
}
public class PhoneController
{
private Phone _phone;
public PhoneController(Phone phone)
{
_phone = phone;
}
}
[TestClass]
public class PhoneControllerTests
{
[TestMethod]
public void TestMethod1()
{
// How mock Phone class?
//var mock = Substitute.For<Device, IPhone>();
//usage of mock
//var controller = new PhoneController(mock);
}
}
第二种情况:
控制器使用抽象类的GetStatus方法Device,因此_phone不能更改为IPhone类型
public abstract class Device
{
protected string Address { get; set; }
public abstract string GetStatus();
}
public interface IPhone
{
void MakeCall();
}
public class Phone : Device, IPhone
{
public void MakeCall()
{
throw new NotImplementedException();
}
public override string GetStatus()
{
throw new NotImplementedException();
}
}
public class PhoneController
{
private Phone _phone;
public PhoneController(Phone phone)
{
_phone = phone;
}
public string GetDeviceStatus()
{
return _phone.GetStatus();
}
public void MakeCall()
{
_phone.MakeCall();
}
}
[TestClass]
public class PhoneControllerTests
{
[TestMethod]
public void TestMethod1()
{
// How mock Phone class?
//var mock = Substitute.For<Device, IPhone>();
//usage of mock
//var controller = new PhoneController(mock);
}
}
C#
largeQ
相关分类