Quantcast
Channel: Fluent Assertions
Viewing all 1402 articles
Browse latest View live

New Post: Throw custom exception on failed assertions

$
0
0

Hi,

The library hasn't been designed for that, but the actual exception class that is thrown upon a verification failure was designed to be pluggable. Unfortunately, the AssertionHelper class is internal. You could file a change request or fork the repository and create a pull request that we could incorporate in the library.


Created Issue: ShouldNotThrow hides stack trace of thrown exception [12473]

$
0
0
When an assertion of the `ShouldNotThrow` family of extension methods fails, the specifics of where in the SUT the exception was thrown is lost. This makes it hard to diagnose because you either need to attach a debugger, or remove the assertion to get the information needed to fix the issue.

Consider the following code (assume it is in a TestFixture):

[Test]
public void This_Should_Not_Throw()
{
Action act = ThrowException;
act.ShouldNotThrow();
}

private void ThrowException()
{
throw new Exception();
}

The failure message is:

>> Did not expect any exception, but found a System.Exception with message "Exception of type 'System.Exception' was thrown.".

and the stack trace shows only `This_Should_Not_Throw` followed by Fluent Assertion code.

If I replace the Fluent Assertion with NUnit's Assert.DoesNotThrow(new TestDelegate(act)), the stack trace is equally unhelpful; however I get this message:

>> Expected: No Exception to be thrown
But was: (Exception of type 'System.Exception' was thrown.)
at ExceptionTest.Class1.ThrowException() in c:\Users\adamv\Documents\Visual Studio 11\Projects\ExceptionTest\ExceptionTest\Class1.cs:line 21
at NUnit.Framework.Constraints.ThrowsNothingConstraint.Matches(Object actual)

If I simply take out the assertion and execute the delegate, I get a complete stack trace.

I would expect Fluent Assertions to provide the stack trace as part of the message in a way similar NUnit. Without this functionality it is better to use the NUnit assertion or use no assertion at all.

Source code checked in, #8b5ebba9c800

$
0
0
Updated the main version to 2.1.0

New Post: asserting the value of an xml element

$
0
0

lets say i have the following xml

<contacts><contact><name>Bob</name><addresspostalAddress="true"><street>123 Smith st</street><address></contact></contacts>

How do i assert that the content of the Street element is "123 Smith st"?

Commented Issue: add new string assertion .Should().BeInFormat(format, args) [12467]

$
0
0
This is similar to wildcards, but I think it will be useful too. If maintainers says ok for that I will be happy to contribute an implementation.


Comments: Sounds like a nice addition.

New Post: Mappings in object graph comparisons

$
0
0

I have a couple of object graph comparison cases that I'm struggling to set up with the Fluent Assertions library.  Both involve some level of advanced mapping from an object (and Entity Framework entity in this case) to its corresponding DTO.

Case 1: Using the documentation's example of Order and OrderDto, let's say that Product as an associated Manufacturer with a Name property (o.Product.Manufacturer.Name).  The ProductDto, though, just has a ManufacturerName property on it instead of an associated ManufacturerDto (i.e. dto.Product.ManufacturerName = o.Product.Manufacturer.Name).

Case 2: Assume that CustomerDto has a name property on it.  The underlying Customer object, though, is split into a FirstName and LastName that are combined when creating the DTO (i.e. dto.Customer.Name = o.Customer.FirstName + " " + o.Customer.LastName).

It looks like these cases can be handled by creating appropriate IMatchingRule and IAssertionRule classes and plugging them in with the Using() method.  Is there some more (for lack of a better word) "fluent" way to do this?  Something like:

orderDto.ShouldBeEquivalentTo(order,
    opt => opt
        .MappingProperty(dto => dto.Product.ManufacturerName).ToProperty(o => o.Product.Manufacturer.Name)
        .MappingProperty(dto => dto.Customer.Name).ToValue(o => o.Customer.FirstName + " "+ o.Customer.LastName));

Or maybe:

orderDto.ShouldBeEquivalentTo(order,
    opt => opt
        .WhereProperty(dto => dto.Product.ManufacturerName, (val, o) => val.Should().Be(o.Product.Manufacturer.Name))
        .WhereProperty(dto => dto.Customer.Name, (val, o) => val.Should().Be(o => o.Customer.FirstName + " "+ o.Customer.LastName)));

I may have just missed something obvious, so I figured I would ask before I start writing extensions or forking and hacking.

Many thanks for the library.  I wish I had discovered it a year ago.

New Post: Mappings in object graph comparisons

$
0
0

Hi leoghann,

Thanks for taking the time to properly formulate your question. What you might want to do is use theUsing-When methods of the options object. The EquivalencySpecs you'll find some examples like these:

            Action act = () => subject.ShouldBeEquivalentTo(expectation, options => options
                .Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
                .When(info => info.PropertyPath.EndsWith("Date")));

 or

            Action act = () => subject.ShouldBeEquivalentTo(expectation, options => 
                options
                .Using<DateTime>(ctx => ctx.Subject.Should().BeCloseTo(ctx.Expectation, 1000))
                .WhenTypeIs<DateTime>());


If you really want to make it fluent, I would rewrite your example as

orderDto.ShouldBeEquivalentTo(order,
    opt => opt
        .Where(dto => dto.Product.ManufacturerName).ShouldMapTo(o => o.Product.Manufacturer.Name)
        .Where(dto => dto.Customer.Name).ShouldHaveValue(o => o.Customer.FirstName + " " + o.Customer.LastName));
Hope that helps,

Dennis

New Post: asserting the value of an xml element

$
0
0

Hi nitro52,

Sorry for the delayed response. Unfortunately, it is not yet possible to verify the contents of a particular element. As an alternative, you could do something similar by finding the XElement that represents its state and invoke an ordinary string assertion streetElement.Value.Should().Be("123 Smith st");

Regards,

Dennis


New Post: name or description of the object being tested?

$
0
0

You can provide some context about the subject-under-test you are asserting by setting the static Verification.SubjectName property. However, you must make sure you set that property to null to prevent influencing another assertion. To actually change the 'object' into something more specific a code change is required.

Let me know what you think...

Dennis

New Post: Comparing two IEnumerables for Properties is not working

$
0
0

Don't worry about that. As long as you're a happy user ;-)

New Post: Mappings in object graph comparisons

$
0
0

I did see the Using-When examples.  For a single object, it looks I could do something like this:

 

orderDto.ShouldBeEquivalentTo(order, options =>
    options
        .Using<string>(ctx => ctx.Subject.Should.Be(order.Product.Manufacturer.Name))
        .When(info => info.PropertyPath.EndsWith("ManufacturerName")));

I have cases, though, where I'm going to be comparing collections of objects.  That left me trying to figure out how to get to the individual objects being compared during a ShouldAllBeEquivalentTo call.  Having looked at it again, though, it looks like I could just manually iterate the collections and use something like the above example to compare them.

for (var i = 0; i < results.Count; i++)
{
    orderDtos[i].ShouldBeEquivalentTo(orders[i], options => options /* Using-When code here */);
}

(I'd need to compare the counts of the two collections as well, but for some reason the code editor keeps having problems when I try to put in ShouldHaveCount.)

Edit: That doesn't seem to work like I thought it would.  If I try to run it as written, I get an exception that subject has a property the other object doesn't have.  If I add in .ExcludeMissingProperties() the test gives a false success.

Reviewed: Release 2.0.0 (Dec 30, 2012)

$
0
0
Rated 5 Stars (out of 5) - Thank you for making our lives easier! I've been using this project for along time and it's just such a wonderful thing to work with, thanks a million!

Commented Issue: Fluent Assertions should not format exceptions using the default formatter [12461]

$
0
0
We use a custom ApplicationErrorException which implements IEnumerable returning a list of parameters associated with that exception.

When the verification fails Fluent Assertions formats the exception using the default formatter, which can result in a message like:

Expected System.ApplicationException, but found {[EntityType, Book], [Key, 123]}.

Which is obviously not providing enough information.
Comments: How do you propose we deal with this?

Commented Issue: BeOfTypeImplements to test IEnumerable instead of specific implementation (list/dictionary) [12463]

$
0
0
Unit tests for my controller include type validation of the model.
I first attempted:
ViewResult.Model.Should().BeOfType<IEnumerable<model>>()

but it failed, stating that the type is List<model>
This is true, but I don't want to worry about that during my testing... I just need to verify that the model is IEnumerable

As a result, I must use:
ViewResult.Model.GetType().Implements<IEnumerable<model>>().Should().BeTrue()

I would prefer something along the lines of:
- some sort of optional parameter for the BeOfType() to allow classes that inherit/implement T
or
- BeOfTypeImplementing<>


PS: keep up the great work... FA is probably my most frequently used nuget package :)
Comments: Is that an answer to your question?

Commented Issue: Output text of a collection assertion should be more friendly [12466]

$
0
0
The output text of a collection assertion (Should().BeEquivalentTo()) should describe specific differences in objects like ShouldHave().AllProperties().EqualTo() does.
Comments: Sorry for not getting back to you earlier. Can you please elaborate a bit more? What kind of output do you expect?

New Post: ShouldBeEquivalentTo method still relies on override of Object.Equals()?

$
0
0

I have a class, let's call it Foo, that is a value type and hence overrides the Equals/GetHashCode() methods. In a separate test fixture, I want to assert thatall the properties on Foo have been set properly, not just the properties used for equality. For this reason, my test assertion specifically uses the ShouldBeEquivalentTo method, which the documentation suggests will consider two objects to be equivalent if "both object graphs have equally named properties with the same value, irrespective of the type of those objects."

However, it appears that ShouldBeEquivalentTo invokes Foo.Equals method, gets a true result and then proceeds to short-circuit the reflection based property matching that ShouldBeEquivalentTo promises.

Is this expected behavior?  If so, in inspecting the FA source, I saw no easy way to alter this behavior (IEquivalencyStep is declared internal).  Are there any other ways to alter this behaviour?

New Comment on "Documentation"

$
0
0
Typo: "Action act = () => subject.Foo2("Hello"); Act.ShouldThrow<InvalidOperationException>() .WithInnerException<ArgumentException>() .WithInnerMessage("whatever");" The variable is called "act", not "Act". Cheers! :)

Commented Issue: CollectionAssertions.HaveCount never calls Count property, always Enumerates [12469]

$
0
0
FIrst off, I'm checking out your repo and I'll supply a fix with this issue... tagged in a pull request?

Gents,

public AndConstraint<TAssertions> HaveCount(int expected, string reason = "", params object[] reasonArgs)
{
...
int num = Enumerable.Count<object>(Enumerable.Cast<object>((IEnumerable) this.Subject));
...
}

is no good. In that call to Linq.Enumerable.Cast() --a function which isn't strictly a cast-- you're getting a yielded value from Subject, a type that doesn't actually relate to the original type of Subject. You cant use an uncasted Subject because Count requires a typed IEnumerable, not an untyped one.

I think the best solution is to do a couple things:
- Make HaveCount virtual.
- Have the non-generic one do the type checking to find the best method (either the property Count or manually enumerating via Count()).
- Have the GenericCollectionAssertions() override the Non-generic one and simply call Linq.Enumerable.Count() with an un-modified Subject.

So branch and pull request pending?

Comments: Bump, manually created stub classes in the fixture. No more Fluent assertions stuff.

Commented Issue: CollectionAssertions.HaveCount never calls Count property, always Enumerates [12469]

$
0
0
FIrst off, I'm checking out your repo and I'll supply a fix with this issue... tagged in a pull request?

Gents,

public AndConstraint<TAssertions> HaveCount(int expected, string reason = "", params object[] reasonArgs)
{
...
int num = Enumerable.Count<object>(Enumerable.Cast<object>((IEnumerable) this.Subject));
...
}

is no good. In that call to Linq.Enumerable.Cast() --a function which isn't strictly a cast-- you're getting a yielded value from Subject, a type that doesn't actually relate to the original type of Subject. You cant use an uncasted Subject because Count requires a typed IEnumerable, not an untyped one.

I think the best solution is to do a couple things:
- Make HaveCount virtual.
- Have the non-generic one do the type checking to find the best method (either the property Count or manually enumerating via Count()).
- Have the GenericCollectionAssertions() override the Non-generic one and simply call Linq.Enumerable.Count() with an un-modified Subject.

So branch and pull request pending?

Comments: Huh? What does that mean? We are going to include your pull request in the next version you know...

New Post: I want to test for property value by property name

$
0
0

I'm trying to use FluentAssertions together with SpecFlow.

And I want to be able to have statements which say: 

the <propertyName> should have <value>

 

As such I want to compare 2 objects to make sure they have matching properties where the propertyName is specified using a string.

Is this possible?

 

Viewing all 1402 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>