Compare a collection's item (like a DateTimeOffset) with FluentAssertions' Contain more specifically with Should

19 Views Asked by At

I "just" want to parse and compare a DateTime(Offset) from a string and check whether it is in a List of collections with FluentAssertions. .Should() is easy enough to use for comparing whether there is an element of that type. However, as I am comparing times I also want to .BeCloseTo with an offset as the time may not be that accurate and I don't care how accurate it is.

CronExpressions comntains a Raw property that represents the string as a DateTime(Offset). (And even if not, let's just assume it does. A test failure would tell me.)


        [Test]
        public void SchedulesItselfForNow()
        {
            this.job = new Job();

            this.job.MetaData.CronExpressions.Should().Contain(x =>
                DateTimeOffset.Parse(x.Raw).Should().BeCloseTo(DateTimeOffset.Now, TimeSpan.FromMinutes(1))
            );
        }

I already asked ChatGPT and the only solution it presented to me, was this as a slight refactoring:

        [Test]
        public void SchedulesItselfForNow()
        {
            this.job = new Job();

            this.job.MetaData.CronExpressions
                .Select(x => DateTimeOffset.Parse(x.Raw))
                .Should()
                .Contain(date => date.Should().BeCloseTo(DateTimeOffset.Now, TimeSpan.FromMinutes(1)));
        }

Idea

I know I can use .Which, but for that I have to have a working (usual boolean) assertion/comparison before. In my case, I don't have this, I just want to compare the string directly:

        [Test]
        public void SchedulesItselfForNow()
        {
            this.job = new Job();

            this.job.MetaData.CronExpressions
                .Select(x => DateTimeOffset.Parse(x.Raw))
                .Should()
                .Contain(date => true) // but what to use here?
                .Which.Should().BeCloseTo(DateTimeOffset.Now, TimeSpan.FromMinutes(1));
        }
1

There are 1 best solutions below

0
rklec On

Ah, this answer lead me to the ...Satisfy methods, and this seems to do what i want:

        [Test]
        public void SchedulesItselfForNow()
        {
            this.job = new Job();

            this.job.MetaData.CronExpressions
                .Select(x => DateTimeOffset.Parse(x.Raw))
                .Should()
                .SatisfyRespectively(x => x.Should().BeCloseTo(DateTimeOffset.Now, TimeSpan.FromMinutes(1)));
        }