Skip to content

Commit

Permalink
Fix ThrowsNothing losing its strong typing to its object type (#1772)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomhurst authored Feb 5, 2025
1 parent 3f655e4 commit 91d2f35
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 4 deletions.
26 changes: 26 additions & 0 deletions TUnit.Assertions.Tests/Bugs/Tests1770.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
using TUnit.Assertions.AssertConditions.Throws;

namespace TUnit.Assertions.Tests.Bugs;

public class Tests1770
{
[Test]
public async Task Throws_Nothing_Keeps_Type()
{
var guid = await Assert.That(Guid.NewGuid).ThrowsNothing();

await Assert.That(guid.ToByteArray()).IsNotEmpty();
}

[Test]
public async Task Throws_Nothing_Keeps_Type_Async_Delegate()
{
var guid = await Assert.That(async () =>
{
await Task.CompletedTask;
return Guid.NewGuid();
}).ThrowsNothing();

await Assert.That(guid.ToByteArray()).IsNotEmpty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ internal CastableAssertionBuilder(InvokableAssertionBuilder<TActual> assertionBu
{
try
{
return (TExpected)Convert.ChangeType(data.Result, typeof(TExpected))!;
return (TExpected?)data.Result;
}
catch
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@
namespace TUnit.Assertions.AssertionBuilders;

public class ValueDelegateAssertionBuilder<TActual>
: AssertionBuilder,
IDelegateSource,
IValueSource<TActual>
: AssertionBuilder, IValueDelegateSource<TActual>
{
internal ValueDelegateAssertionBuilder(Func<TActual> function, string? expressionBuilder) : base(function.AsAssertionData(expressionBuilder), expressionBuilder)
{
Expand Down
8 changes: 8 additions & 0 deletions TUnit.Assertions/Assertions/Throws/ThrowsExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,14 @@ public static class ThrowsExtensions
assertionData => assertionData.Result);
}

public static CastableAssertionBuilder<TActual, TActual> ThrowsNothing<TActual>(this IValueDelegateSource<TActual> delegateSource)
{
IValueSource<TActual> valueSource = delegateSource;
return new CastableAssertionBuilder<TActual, TActual>(
valueSource.RegisterAssertion(new ThrowsNothingAssertCondition<TActual>(), []),
assertionData => assertionData.Result is TActual actual ? actual : default);
}

public static ThrowsException<TActual, TException> WithParameterName<TActual, TException>(this ThrowsException<TActual, TException> throwsException, string expected, [CallerArgumentExpression(nameof(expected))] string? doNotPopulateThisValue = null)
where TException : ArgumentException
{
Expand Down

0 comments on commit 91d2f35

Please sign in to comment.