Question

I've got a method in a class that's writing to some string, which calls another method which does the same. Something like:

void foo() {
  a += "xyx";
  bar();
}

void bar() {
  a += "abc";
}

For unit testing purposes, I want to test foo and bar separately. Is there any way to prevent bar from being run when I call foo() or to replace it with another method?

Was it helpful?

Solution

Create a subclass that overrides bar() that does nothing.

OTHER TIPS

Why would you want to do that?

You could intercept the code at the byte code level using aspects (not wise); you could take in an object that calls bar: void foo(MyBarObject m) { a += "xyx"; m.bar(); }

But, as I said, I can't think why this is useful. A unit test is meant to test a public interface. If bar() is private or protected, then it's tested automatically via your call, and later assertions, to foo(). If both foo() and bar() are public, cool, test them separatley.

Can you post a real example? Can you change the code under test? Etc.

One could argue that the above example isn't testable code. Instead, if the code were:

void foo() {
  a += "xyx";
}

void bar() {
  a += "abc";
}

void fooBar() {
  foo();
  bar();
}

it would be easy to unit test.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top