单元测试返回void的方法

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)

注意:

  • 方法名称= AuthoriseDeviceProfile返回void
  • 该方法检查userSentMakeModel与db匹配中存储的那个
  • 如果它匹配 - 它只是返回(即不改变任何状态)

我们如何对这种方法进行单元测试?

  • 嘲笑了回购
  • 涵盖了"THROWS EXCEPTION"的场景
  • 问题是如何对所有WENT WELL即用户的场景进行单元测试; s makeModel与repository匹配; s makeModel

任何设计建议,以使这个可测试是非常欢迎提前感谢.

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)


Jon*_*eet 7

如果一个方法是无效的,那么它应该有一些可观察到的副作用 - 否则它是毫无意义的.因此,不测试返回值,而是测试副作用.在这种情况下,看起来可能是在哪些情况下抛出异常.

(这里,"抛出异常"被视为副作用;你当然也可以认为它是一种隐含的返回值......)


Zdr*_*nev 5

注入一个模拟的存储库.测试是否调用存储库上的某些方法.