Unit Testing - Effective Tips With bUnit Testing

Posted by Unit Testing - bUnit Testing with Blazor C# on January 21, 2025

As I did some bUnit Testing for several weeks, I found that some methods are private (which can't easily be tested, a later post will be made on this), and some methods can't be tested because it relies on another button (or method invocation) to then allow it be tested. I am focusing on the later on this, and I have included some tips to code to unit test with bUnit below: -

       [Fact]
       public void ShouldSetHasNavIconBeenClickedToTrue()
       {
           // Arrange
           _renderedComponent = RenderComponent<Class>(parameters => parameters
               .Add(p => p.HasNavIconBeenClicked, true));

           // Act
           var hasNavIconBeenClicked = _renderedComponent.Instance.HasNavIconBeenClicked;

           // Assert
           Assert.True(hasNavIconBeenClicked);
       }

       [Fact]
       public async Task ShouldOpenNavMenuEventCallBack()
       {
           // Arrange
           bool callbackInvoked = false;
           var callback = EventCallback.Factory.Create(this, () => callbackInvoked = true);

           _renderedComponent = RenderComponent<Class>(parameters => parameters
               .Add(p => p.HasNavIconBeenClicked, true)
               .Add(p => p.OpenNavMenuEventCallBack, callback));

           // Act
           await _renderedComponent.Instance.OpenNavMenuEventCallBack.InvokeAsync();

           // Assert
           Assert.True(callbackInvoked);
       }

       [Fact]
       public void ShouldDismissEditWorkspaceIconButton()
       {
           // Arrange
           var menuButton = _renderedComponent.Find("#MenuButton");
           // Check Actions Menu button clickable in context

           // Act
           menuButton.Click();

           // Assert
           var editTitleComponent = _renderedComponent.Find("#EditWorkspaceTitleButton");
           Assert.NotNull(editTitleComponent);
           editTitleComponent.Click();

           var dismissEditWorkspaceIconButton = _renderedComponent.Find("#DismissEditWorkspaceIcon");
           Assert.NotNull(dismissEditWorkspaceIconButton);

       }

Some useful code