我正在尝试通过 Moq 在我的项目(.net core 3.1)中测试 ILogger(Microsoft.Extensions.Logging),但是...它失败了..我试图捕获代码中的异常:
try{
//do something
}
catch (Exception e)
{
_logger.LogError(new
{
RequestId = requestId.ToString(),
Topic = "Merge files",
Message = "process failed",
Status = "Failed"
}, e);
}
Run Code Online (Sandbox Code Playgroud)
我定义了模拟记录器
private readonly Mock<ILogger<MyClass>> _logger = new Mock<ILogger<MyClass>>();
Run Code Online (Sandbox Code Playgroud)
这是我的 UT
_logger.Verify(
x => x.Log(
It.IsAny<LogLevel>(),
It.IsAny<EventId>(),
It.Is<It.IsAnyType>((v, t) => true),
It.IsAny<Exception>(),
It.Is<Func<It.IsAnyType, Exception, string>>((v, t) => true)), Times.Once);
Run Code Online (Sandbox Code Playgroud)
我调试了它,在我的代码中执行了日志异常方法,但最后 UT 失败,因为我收到以下消息:
预期在模拟上调用一次,但实际调用次数为 0 次: x => x.Log<It.IsAnyType>(It.IsAny(), It.IsAny(), It.Is<It.IsAnyType>((v, t) => True), It.IsAny(), It.Is<Func<It.IsAnyType, Exception, string>>((v, t) …
我想通过模拟两个MailMessage和使用moq测试下面的方法SmptpClient
public void SendEmail(string emailAddress, string subject, string body)
{
using (var mail = new MailMessage(NoReplyEmailAddress, emailAddress))
{
mail.Subject = subject;
mail.Body = body;
mail.IsBodyHtml = true;
using (var client = new SmtpClient())
{
client.Host = SmtpHost;
client.Port = SmtpPort;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.Send(mail);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的测试方法是:
public void TestSendEmail()
{
Mock<MailMessage> mailMessageMock = new Mock<MailMessage>();
MailMessage message = (MailMessage)mailMessageMock.Setup(m => new MailMessage()).Returns(mailMessageMock.Object);
Mock<SmtpClient> smtpClientMock = new Mock<SmtpClient>();
smtpClientMock.Setup(s => new SmtpClient()).Returns(smtpClientMock.Object);
EmailService emailService = new …Run Code Online (Sandbox Code Playgroud) 以下构造函数参数没有用于使用 moq 和 xunit 进行单元测试的匹配装置数据。
已经使用依赖注入和模拟来测试类。
//this is how i register the DI.
services.AddScoped<IWaktuSolatServiceApi, WaktuSolatServiceApi>();
public interface IWaktuSolatServiceApi
{
Task<Solat> GetAsyncSet();
}
// the unit test.
public class UnitTest1
{
Mock<IWaktuSolatServiceApi> waktu;
public UnitTest1(IWaktuSolatServiceApi waktu)
{
this.waktu = new Mock<IWaktuSolatServiceApi>();
}
[Fact]
public async Task ShoudReturn()
{
var request = new Solat
{
zone = "lala"
};
var response = waktu.Setup(x =>
x.GetAsyncSet()).Returns(Task.FromResult(request));
}
}
Run Code Online (Sandbox Code Playgroud)
但是我收到此错误以下构造函数参数没有匹配的夹具数据。
验证方法测试调用失败: .Net Core 3.1、Framework 4.8
正在测试的方法:为简洁起见,代码简化。
public bool IsValidPhoneNumber(string value)
{
return value.Length == 10;
}
Run Code Online (Sandbox Code Playgroud)
完整的测试类(通过):
public class CustomersViewModelTest
{
private CustomerViewModel _sut;
private readonly Mock<ICustomerViewModel> _customerViewModel;
private readonly Mock<ICustomerRepository> _customerRepository;
private readonly Mock<IMapper> _mapper;
public CustomersViewModelTest()
{
_customerViewModel = new Mock<ICustomerViewModel>();
_customerRepository = new Mock<ICustomerRepository>();
_mapper = new Mock<IMapper>();
_sut = new CustomerViewModel(_customerRepository.Object, _mapper.Object);
}
[Fact]
public void PhoneNumberTest()
{
string phoneNumber = "123456789";
_customerViewModel.Setup(x => x.IsValidPhoneNumber(phoneNumber)).Returns(false);
bool result = _sut.IsValidPhoneNumber(phoneNumber);
Assert.False(result);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,如果我尝试验证方法调用,测试将失败:(断言被删除) …
我是 TDD 新手,能否请您使用 moq 编写测试用例以获取以下代码 -
public async Task<Model> GetAssetDeliveryRecordForId(string id)
{
var response = await client.GetAsync($"api/getdata?id={id}");
response.EnsureSuccessStatusCode();
var result = await response.Content.ReadAsAsync<Model>();
return result;
}
Run Code Online (Sandbox Code Playgroud)
提前致谢。
.NET 中是否有任何可以模拟系统时间的模拟库,无论哪个模拟库对我来说都可以,例如 moq 等?