allenylzhou
allenylzhou

Reputation: 1461

How do I unit test a function that loops over objects?

Let me explain myself.

function insertObjects($objs) {
    foreach ($objs as $obj) {
        $this->repository->insert($obj);
    }
}

I don't want to test that insertion into the database worked because I assume it works (it's a different unit). I also don't want to test foreach because obviously foreach is going to work. So the only thing to test here is that $objs is a well formed array. But if $objs is the mock data that I will be passing in... so does this mean there is nothing to test for this function?

Upvotes: 2

Views: 2636

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97151

If there's any chance of invalid input (a not well-formed array, null value, etc.), you need to handle that case in your method by explicitly checking for it.

In your test, you would then try to call your method with various invalid values, and check whether your method responds correctly, i.e. the database insert method is not called, exceptions are thrown, errors are logged, etc.

Other than that, the only thing to test is whether your database insert method is called with the parameters that correspond to the values in the valid test array you pass in.

Upvotes: 1

Related Questions