c# - 是否可以对这种方法进行单元测试
问题描述
我正在努力解决单元测试和模拟问题。因此,正如我所拥有的,单元测试,使用提供的参数测试单个方法,期望使用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 };
}
如果有人可以向我解释如何为这样的事情编写单元测试,将不胜感激;因为互联网上的大多数文章只是以基本的计算器为例,当涉及到这样的“复杂”方法时,这根本没有帮助。
解决方案
推荐阅读
- javascript - javascript:由于通配符,获取被 CORS 策略阻止
- angular - 重定向到 url 中特殊页面中的 angular pwa
- java - 尝试使用 Maven 在 JOOQ 中实现 EnumConverter 时出错
- javascript - 动态更改标题中的元标记?
- node.js - 不起作用发送 res.status(409).send('error')
- java - 如何在接口上有效地利用继承和多态
- python-3.x - 使用子键分配字典值
- reactjs - 用于字符串的 React TypeScript Props 接口
- angular - 引导程序未在 chrome 中加载
- git - 完成发布推送到所有远程存储库