首页 > 解决方案 > 是否可以对这种方法进行单元测试

问题描述

我正在努力解决单元测试和模拟问题。因此,正如我所拥有的,单元测试,使用提供的参数测试单个方法,期望使用Assert. 现在,我实现的几乎所有方法都以一种或另一种方式与数据库通信。根据方法中发生的情况,它们中的大多数都有多种响应。也可能会抛出异常,但它们会被 catch 子句捕获并优雅地处理。

我一直在尝试为以下方法编写单元测试,但我认为我没有得到正确的嘲笑。这是有问题的方法:

    public override async Task<RegistrationResponse> RegisterEndpoint(RegistrationRequest request, ServerCallContext context)
    {
        try
        {
            //Check that IP address is valid, returned malformed if not a valid IP
            var isValidIp = System.Net.IPAddress.TryParse(request.IpAddress, out _);
            if (!isValidIp)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Malformed };

            //Check that the record doesn't exist in the DB already
            var doesExist = _context.Services.Any(x => x.IpAddress == request.IpAddress && x.Type == request.Type);
            if (doesExist)
                return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Duplicate };

            //Add the service to the database
            _context.Services.Add(new ServiceModel
            {
                IpAddress = request.IpAddress,
                Type = request.Type,
                LastAccessed = DateTime.Now
            });

            //Save the service to the database
            await _context.SaveChangesAsync();
        }
        catch (Exception ex)
        {
            //Log exception 
            await _logClient.LogException(ex, new object[]{ request });
            //Return failure result
            return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Failure };
        }

        //Return successful result
        return new RegistrationResponse { Result = RegistrationResponse.Types.Result.Success };
    }

如果有人可以向我解释如何为这样的事情编写单元测试,将不胜感激;因为互联网上的大多数文章只是以基本的计算器为例,当涉及到这样的“复杂”方法时,这根本没有帮助。

标签: c#unit-testing

解决方案


推荐阅读