Unit Testing with a Mock User

I am unit testing my login procedures for a Xamarin Forms application and need to test the App.CurrentUser and App.AllUsers methods but I can’t determine how to mock a User object. Does MongoDB have any documentation or examples for unit testing a User in C#?

Seriously - 5 days and no one from Mongo has any advice?

Hi Raymond - we document the user object here, does that help?

Hey Raymond, unfortunately, the app/user interaction is not very mock friendly. There are some internal API to get a fake user which may get you what you need, but you’ll need to access those via reflection:

private static User GetUser(App app, string id)
    var handleField = typeof(App).GetField("Handle", BindingFlags.Instance | BindingFlags.NonPublic);
    var handle = handleField.GetValue(app);

    var getUserForTesting = handle.GetType().GetMethod("GetUserForTesting");

    // Need to be JWTs, but the contents don't matter
    var refreshToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoicmVmcmVzaCB0b2tlbiIsImlhdCI6MTUxNjIzOTAyMiwiZXhwIjoyNTM2MjM5MDIyfQ.SWH98a-UYBEoJ7DLxpP7mdibleQFeCbGt4i3CrsyT2M";
    var accessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoiYWNjZXNzIHRva2VuIiwiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjI1MzYyMzkwMjJ9.bgnlxP_mGztBZsImn7HaF-6lDevFDn2U_K7D8WUC2GQ";

    var userHandle = getUserForTesting.Invoke(handle, new object[] { id, refreshToken, accessToken });

    return (User)Activator.CreateInstance(typeof(User), BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { userHandle, app }, null);

That’s obviously fairly ugly, but should hopefully unblock you. We do plan to make this entire thing easier to mock and test, but since most of the functionality is implemented in C++, it’s a little bit complicated to come up with a good design. That being said, we’d appreciate your feedback on what exactly you’re looking to test there and what would the ideal SDK API look like to enable that.

1 Like

Thanks Nikola, that code did the trick.

I have a Xamarin forms app that logs in the user then passes a Realms.Sync.User to the next page which is then sued to access the data from Realm. I needed a valid mock User object for unit testing and UI tests.

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.