Ven*_*u b 14 c# unit-testing dependency-injection
想要单元测试以下类中的方法
public class DeviceAuthorisationService : IDeviceAuthorisationService
{
private DeviceDetailsDTO deviceDetailsDTO = null;
private IDeviceAuthorisationRepositiory deviceAuthorisationRepositiory;
public DeviceAuthorisationService(IDeviceAuthorisationRepositioryService paramDeviceAuthorisationRepository)
{
deviceAuthorisationRepositiory = paramDeviceAuthorisationRepository;
}
public void AuthoriseDeviceProfile(long paramUserID, string paramClientMakeModel)
{
if (deviceDetailsDTO == null)
GetCellPhoneDetails(userID);
if (deviceDetailsDTO.IsDeviceSelected == false)
throw new SomeCustomExceptionA();
if (deviceDetailsDTO.CellPhoneMakeModel.ToLower() != paramClientMakeModel.ToLower())
throw new SomeCustomExceptionB;
}
public void UpdateDeviceStatusToActive(long userID)
{
if (deviceDetailsDTO == null)
throw new InvalidOperationException("UnAuthorised Device Profile Found Exception");
if (deviceDetailsDTO.PhoneStatus != (short)Status.Active.GetHashCode())
deviceAuthorisationRepositiory.UpdatePhoneStatusToActive(deviceDetailsDTO.DeviceID);
}
private void GetCellPhoneDetails(long userID)
{
deviceDetailsDTO = deviceAuthorisationRepositiory.GetSelectedPhoneDetails(userID);
if (deviceDetailsDTO == null)
throw new SomeCustomException()
}
}
Run Code Online (Sandbox Code Playgroud)
注意:
我们如何对这种方法进行单元测试?
任何设计建议,以使这个可测试是非常欢迎提前感谢.
ale*_*exn 15
由于您的方法返回void,因此可能会有一些可以测试/断言的副作用.
在您的情况下,一个选项是提供一个模拟实例IDeviceAuthorisationRepositioryService
.然后,您可以检查是否UpdatePhoneStatusToActive
已发生呼叫.这是使用Moq的解决方案:
var mock = new Mock<IDeviceAuthorisationRepositioryService>();
var service = new DeviceAuthorisationService(mock.Object);
service.UpdateDeviceStatusToActive(....);
mock.Verify(x => service.UpdatePhoneStatusToActive(), Times.Never());
Run Code Online (Sandbox Code Playgroud)
如果一个方法是无效的,那么它应该有一些可观察到的副作用 - 否则它是毫无意义的.因此,不测试返回值,而是测试副作用.在这种情况下,看起来可能是在哪些情况下抛出异常.
(这里,"抛出异常"被视为副作用;你当然也可以认为它是一种隐含的返回值......)