How to perform unit testing on an app that uses mongodb?

How to perform unit testing on an app that uses mongodb?

How mock a mongodb in golang?

IMO if your tests need to start a database, they are not unit tests.

What is the unit of functionality you want to test in your code?

This

func DeleteUser(w http.ResponseWriter, r *http.Request) {
userID := chi.URLParam(r, "userID")
context := NewContext()
defer context.Close()
c := context.DbCollection("users")
userRepo := &data.UserRepository{c}
err := userRepo.Delete(userID)
if err != nil {
	common.DisplayAppError(
		w,
		err,
		"Un error inesperado ha ocurrido",
		500,
	)
	return
} else {
	w.WriteHeader(http.StatusNoContent)
}

}

That call this

func (r *UserRepository) Delete(id string) error {
err := r.C.Remove(bson.M{"_id": bson.ObjectIdHex(id)})
return err

}

It feels like you have two problems. The first is how to inject (or invert) the direct dependency on your data.UserRepository type. The second is how to assert that MongoDB db deleted the record that you asked for.

I would approach the second by not doing it, that is your MongoDB driver has tests for this, trust them.

This leaves you with the first problem of testing that a method on a type is called when you hit a controller which can be replaced by testing that a method on a mock impl you provide is called. Have a look at the recent thread on the Lake framework for a suggestion how to inject a dependency into a controller.

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