Skip to content

Document testing components that use native dependencies #511

@egil

Description

@egil

Document the how native dependencies will work in a bUnit context.


Original issue text:

Components that use native dependencies cannot be rendered with bUnit.

Simple example (lifted from here):

Let’s add a simple native C function to a Blazor WebAssembly app:

  1. Run dotnet workload install wasm-tools
  2. Create a new Blazor WebAssembly project.
  3. Add a Test.c file to the project.
  4. Add a C function in Test.c for computing factorials:
int fact(int n)
{
    if (n == 0) return 1;
    return n * fact(n - 1);
} 
  1. Add a NativeFileReference for Test.c in your project file:
<ItemGroup>
  <NativeFileReference Include="Test.c" />
</ItemGroup>
  1. In Pages/Index.razor add a DllImport for the fact function in generated Test library:
@using System.Runtime.InteropServices
...razor
@code {
    [DllImport("Test")]
    static extern int fact(int n);
}
  1. Call fact method from your .NET code.
<p>@fact(3)</p>
  1. Add a xunit project and add bUnit to it
  2. Create a simple test that renders the Index component:
public class UnitTest1 : TestContext
{
    [Fact]
    public void Test1()
    {
        var cut = RenderComponent<Index>();
    }
}
  1. Doing a dotnet test yields the following error message:
System.DllNotFoundException : Unable to load DLL 'Test' or one of its dependencies: The specified module could not be found. (0x8007007E)

Options 1 - dont support it

For now, I am content with just telling users to wrap their extern calls in an abstract that they inject into the components that needs it, and then mock/fake that during testing.

Metadata

Metadata

Assignees

No one assigned

    Labels

    documentationImprovements or additions to documentationgood first issueGood for newcomers

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions