Search code examples
c#unit-testingexceptionnunitnsubstitute

How to test if function does not throw exception?


I have this function and test:

public void SaveForWeb ()
{
    UpdateGameState();
    try
    {
        PlayerPrefs.SetFloat(Helper.EXP_KEY, experience);
        PlayerPrefs.SetFloat(Helper.SCORE_KEY, score);
        // other properties that need to be saved in PlayerPrefs

        PlayerPrefs.Save();
    }
    catch (Exception ex)
    {
        Debug.Log(ex.Message);
    }
}

[Test]
[Category(Helper.TEST_CATEGORY_SAVE_FOR_WEB)]
public void SaveForWebTest ()
{
    // arrange
    var slgdController = FakeSaveLoadGameDataController();
    TestDelegate myDelegate = () => {};

    // act
    slgdController.SaveForWeb();

    // assert
    Assert.DoesNotThrow(myDelegate);
}

But I feel there is no connection between the assertion and the call of SaveForWeb() function.

Note: SaveForWeb() uses PlayerPrefs from the Unity3D API which might throw PlayerPrefsException if the local file exceedes 1 MB.

Is this the right way to assert if function does not throw exception?


Solution

  • You don't have to assert if the method doesn't throw. I know you're using NUnit, but there's a xUnit issue that describes why you don't need to assert it.

    However, if you want to be explicit, you can do:

    [Test]
    [Category(Helper.TEST_CATEGORY_SAVE_FOR_WEB)]
    public void SaveForWebTest ()
    {
        // arrange
        var slgdController = FakeSaveLoadGameDataController();
    
        Assert.DoesNotThrow(() => slgdController.SaveForWeb());
    }