I have an integration test in my project that should use DateTime.Now
.
This is my method:
public static ErrorResult CheckAvailabiliteOfOrderDeliveryInCurrentTime(string openingTime,string closingTime)
{
var currentTimeString = System.DateTime.Now.ToString("HH:mm:ss");
if (DateTime.Parse(openingTime + ":00") > DateTime.Parse(closingTime + ":00"))
{
if ((DateTime.Parse(currentTimeString) <= DateTime.Parse("23:59:00") &&
DateTime.Parse(currentTimeString) > DateTime.Parse(openingTime + ":00")) ||
(DateTime.Parse(currentTimeString) < DateTime.Parse(closingTime + ":00") &&
DateTime.Parse(currentTimeString) >= DateTime.Parse("00:00:00")))
{
return ErrorResult.None;
}
else
{
return ErrorResult.OutOfDeliveryTime;
}
}
else
{
if (DateTime.Parse(currentTimeString) < DateTime.Parse(closingTime + ":00") &&
DateTime.Parse(currentTimeString) > DateTime.Parse(openingTime + ":00"))
{
return ErrorResult.None;
}
else
{
return ErrorResult.OutOfDeliveryTime;
}
}
}
My handler method that call this method:
public async Task<OrderDto> Handle(CreateOrderCommand request, CancellationToken cancellationToken)
{
var validator = new CreateOrderCommandValidator();
var result = await validator.ValidateAsync(request, cancellationToken).ConfigureAwait(false);
if (!result.IsValid)
throw new ValidationException(result);
var foodBusiness = await _context.FoodBusinesses.FindAsync(Guid.Parse(request.FoodBusinessId));
if (foodBusiness == null)
throw new NotFoundException(nameof(FoodBusiness), request.FoodBusinessId);
if (request.Type == OrderTypes.Delivery)
{
var isOutdeliveryTime = DateTimeHelpers.CheckAvailabiliteOfOrderDeliveryInCurrentTime(foodBusiness.OpeningTime, foodBusiness.ClosingTime);
if (isOutdeliveryTime == ErrorResult.OutOfDeliveryTime)
{
var newOrder = new OrderDto();
newOrder.errorDeliveryTimeAvailabilite = ErrorResult.OutOfDeliveryTime;
return _mapper.Map<OrderDto>(newOrder);
}
else
{
var newOrder = await ExecuteOrderOperations(request, cancellationToken, foodBusiness);
return _mapper.Map<OrderDto>(newOrder);
}
}
else
{
var newOrder = await ExecuteOrderOperations(request, cancellationToken, foodBusiness);
return _mapper.Map<OrderDto>(newOrder);
}
}
By default application us using System.DateTime.Now
, but in the integration test, I need to use my own DateTime.Now
- is there any solution for this? Thanks
Your opinions are:
ISystemClock
and have your unit test use a mock.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.