Bryson Thill
Bryson Thill

Reputation: 531

How can you test that a function is invoking another function?

I'm new to unit testing, especially in Dart/Mockito, so maybe I'm approaching this all wrong. I have an authentication system that has a registerPreLogoutCallback(PreLogoutCallback callback) method, which adds the given asynchronous callback to a list. When logOut is called, I use Future.wait to wait until each of these callbacks has executed, then actually log the user out.

When testing the logOut method, I'd like to make sure that any registered callbacks have been called. Therefore, I figured I should call registerPreLogoutCallback a few times in the unit test, and somehow verify that the registered callbacks have been called. Is this possible? Does it violate the purpose of a unit test?

Upvotes: 1

Views: 2119

Answers (1)

Schwern
Schwern

Reputation: 164699

If part of logOut's definition is that it calls the PreLogoutCallback, then that is part of logOut's unit test. It's fine to use registerPreLogoutCallback as part of the test, but you're not testing registerPreLogoutCallback. Instead, registerPreLogoutCallback gets its own unit test.

logOut's unit test would include something like this vaguely Javascript shaped pseudo-code.

// Set the callback to be a closure around `preLogoutCalled`.
// registerPreLogoutCalled() has its own unit test, we know it works.
var preLogoutCalled = false
registerPreLogoutCallback( function() { preLogoutCalled = true } )

// Logout
logOut()

// Check the callback was called
assert(preLogoutCalled)

If logOut is responsible for passing arguments to the callback, you might put tests in the callback itself to check the callback got the right arguments. Let's say the callback gets the current user.

logged_in_user = ...

registerPreLogoutCallback(
    function(user) { assertEq(user, logged_in_user) }
)

logOut()

The best part is it's entirely black-box. Calling the callbacks is part of logOut's defined behavior. No assumptions need to be made about how logOut() is implemented.

Upvotes: 3

Related Questions