单元测试返回一个空的方法
问题描述:
本想单元测试在以下类中的方法
Wanted to Unit Test a method in the following Class
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()
}
}
请注意:
- 方法名称= AuthoriseDeviceProfile返回void
- 的方法检查userSentMakeModel对存储在数据库中的匹配
- 如果它相匹配的 - 它只是返回(即不会改变任何状态)
我们将如何单元测试这种方法吗?
How will we unit test this method?
- 有嘲笑回购
- 已经覆盖的抛出异常
- 问题是所有方案中如何进行单元测试进行得很顺利,即用户; S makeModel与库匹配; S makeModel
方案
- Have mocked the Repo
- Have covered scenario of "THROWS EXCEPTION"
- Question is how to unit test the scenario of ALL WENT WELL ie user;s makeModel matched with repository;s makeModel
任何设计建议,使这个测试的是最欢迎的
先谢谢了。
Any design suggestions to make this testable is most welcome Thanks in advance.
答
由于你的方法返回void,它可能有一定的副作用,你可以测试/断言上。
Since your method returns void, it probably has some side-effect that you can test/assert on.
在你的情况下,选择将是提供 IDeviceAuthorisationRepositioryService
的模拟实例。然后,您可以检查是否为 UpdatePhoneStatusToActive
通话发生。下面是一个使用的解决方案起订量:
In your case, an option would be to provide a mock instance of IDeviceAuthorisationRepositioryService
. You can then check if a call to UpdatePhoneStatusToActive
has happened. Here is a solution using Moq:
var mock = new Mock<IDeviceAuthorisationRepositioryService>();
var service = new DeviceAuthorisationService(mock.Object);
service.UpdateDeviceStatusToActive(....);
mock.Verify(x => service.UpdatePhoneStatusToActive(), Times.Never());