Grégoire Borel
Grégoire Borel

Reputation: 2028

Mocking parameter of a void method

Suppose I have the following setter:

public void setNewPath(final String path) {
  if (StringUtils.hasText(path) && !path.endsWith(File.separator)) {
            this.newPath = path + File.separator;
        } else {
            this.newPath = path;
        }
    }

I'd like to mock the parameter path in my test method. Is that possible?

Upvotes: 0

Views: 116

Answers (1)

Jeff Bowman
Jeff Bowman

Reputation: 95654

This is not a good problem for mocking. Under no circumstances will the parameter be modified in place, given that Strings are immutable, and though a mock could tell you if a method is called it won't let you track the value across the modifications you'd be making.

As Brian Agnew posted in the comments, "test the method with various inputs, and assert some behaviour (e.g. the setting of newPath)". Make sure that newPath has a getter, even if the getter is only for testing (and is documented as such).

Upvotes: 1

Related Questions