我正在努力使自己绕过单元测试和模拟。因此,就我而言,单元测试使用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 };
}
如果有人可以向我解释如何为此类内容编写单元测试,将不胜感激;因为互联网上的大多数文章都只是以一个基本的计算器为例,而对于“复杂” 这样的方法完全没有帮助。