i'm new in Unit testing. I have to create xUnit test for DataService, which is count _allEntity items after some seconds. I did something like this, but it's not works, because it returns 0. I think moqcked DataService not excetiong at all) Test:
[Fact]
public async Task TestListCountAfterDelay()
{
// Arrange
var expectedCount = 3;
var mockSystemClock = new Mock<ISystemClock>();
var mockDataRepository = new Mock<IDataRepository>();
var dataService = new DataService(mockSystemClock.Object, mockDataRepository.Object);
dataService.StartEntityTask();
// Wait for 6 seconds
await Task.Delay(TimeSpan.FromSeconds(6));
// Act
dataService.StopEntityTask();
// Assert
Assert.Equal(expectedCount, dataService.Allentity.Count);
}
Service:
public class DataService : IDataService
{
private readonly ISystemClock _systemClock;
private readonly IDataRepository _dataRepository;
private CancellationTokenSource cancellationTokenentity;
private IList<DataEntity> _allEntity;
public IList<DataEntity> Allentity => _allEntity;
private readonly string[] entityArray = { "Entity1", "Entity2", "Entity3", "Entity4" };
private int currentobject = 0;
private DateTimeOffset _insertentity;
private const int object_INTERVAL = 2000;
public DataService(ISystemClock systemClock, IDataRepository dataInsertRepository)
{
_dataRepository = dataInsertRepository;
_systemClock = systemClock;
cancellationTokenentity = new CancellationTokenSource();
_allEntity = new List<DataEntity>();
}
private void Processentity(CancellationToken cancellationToken)
{
while (!cancellationToken.IsCancellationRequested)
{
if (_insertentity.Add(TimeSpan.FromMilliseconds(object_INTERVAL)) <= _systemClock.UtcNow)
{
var object = new DataEntity { Name = entityArray[currentobject], DateTime = dateTime_ };
_dataRepository.WriteobjectData(object);
if (!_allEntity.Contains(object))
{
_allEntity.Add(object);
}
currentobject = (currentobject >= (entityArray.Length - 1)) ? 0 : ++currentobject;
_insertentity = _systemClock.UtcNow;
}
}
}
}
public void StartEntityTask()
{
cancellationTokenentity = new CancellationTokenSource();
Task.Run(() => Processentity(cancellationTokenentity.Token));
}
public void StopEntityTask()
{
cancellationTokenentity.Cancel();
}
}
Could you help me, change this test correctly. Thanks.