|
| 1 | +using System; |
| 2 | +using Xunit; |
| 3 | +using DynamicCode.Compiler; |
| 4 | + |
| 5 | +namespace DynamicCode.Test; |
| 6 | + |
| 7 | +public class DynamicCompilerTests |
| 8 | +{ |
| 9 | + [Fact(DisplayName = "CompileFunction<T> compiles and invokes Func<int, int, int> correctly")] |
| 10 | + public void CompileFunction_GenericFuncIntIntInt_Works() |
| 11 | + { |
| 12 | + var code = @"public static class DynamicClass { public static int Calculate(int x, int y) { return x + y; } }"; |
| 13 | + var fn = DynamicCompiler.CompileFunction<Func<int, int, int>>(code); |
| 14 | + Assert.Equal(12, fn(7, 5)); |
| 15 | + } |
| 16 | + |
| 17 | + [Fact(DisplayName = "CompileFunction(Type, code) compiles and invokes Func<string, string, string> correctly")] |
| 18 | + public void CompileFunction_TypeFuncStringStringString_Works() |
| 19 | + { |
| 20 | + var code = @"public static class DynamicClass { public static string Calculate(string a, string b) { return a + b; } }"; |
| 21 | + var funcType = typeof(Func<string, string, string>); |
| 22 | + var fn = DynamicCompiler.CompileFunction(funcType, code); |
| 23 | + var result = fn.DynamicInvoke("Hello", "World"); |
| 24 | + Assert.Equal("HelloWorld", result); |
| 25 | + } |
| 26 | + |
| 27 | + [Fact(DisplayName = "CompileFunction throws on compilation error")] |
| 28 | + public void CompileFunction_ThrowsOnCompilationError() |
| 29 | + { |
| 30 | + var code = @"public static class DynamicClass { public static int Calculate(int x, int y) { return x + ; } }"; |
| 31 | + Assert.Throws<InvalidOperationException>(() => DynamicCompiler.CompileFunction<Func<int, int, int>>(code)); |
| 32 | + } |
| 33 | + |
| 34 | + [Fact(DisplayName = "CompileFunction throws if method not found")] |
| 35 | + public void CompileFunction_ThrowsIfMethodNotFound() |
| 36 | + { |
| 37 | + var code = @"public static class DynamicClass { public static int NotCalculate(int x, int y) { return x + y; } }"; |
| 38 | + Assert.Throws<MissingMethodException>(() => DynamicCompiler.CompileFunction<Func<int, int, long>>(code)); |
| 39 | + } |
| 40 | + |
| 41 | + [Fact(DisplayName = "CompileFunction works with C# alias and CLR types mixed")] |
| 42 | + public void CompileFunction_WorksWithAliasAndClrTypes() |
| 43 | + { |
| 44 | + var code = @"using System; public static class DynamicClass { public static Int32 Calculate(int x, Int32 y) { return x + y; } }"; |
| 45 | + var fn = DynamicCompiler.CompileFunction<Func<int, int, int>>(code); |
| 46 | + Assert.Equal(11, fn(5, 6)); |
| 47 | + } |
| 48 | +} |
0 commit comments