Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if function does not throw exception? [duplicate]

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?

like image 234
Vlad Avatar asked May 11 '26 19:05

Vlad


1 Answers

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());
}
like image 177
Marcio Rinaldi Avatar answered May 13 '26 10:05

Marcio Rinaldi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!