views:

136

answers:

3

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?

+5  A: 

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

Egwor
What would the client code look like? How are you instantiating the class that now overrides bar(). So, you would have to change the code (or the factory) that instantiates the new class. As I said below, I think we need more details on the problem, specifically, can the source be altered.
Adrian Mouat
If you decide to do this, be aware that your test will be testing something slightly different than the class it is supposed to be test. That can lead to holes in your test coverage.
NamshubWriter
+1  A: 

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.

Adrian Mouat
A: 

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.

dcoke23