How to write JUnit for an adapter without complicated code?

I have an adapter from I1to ILoggerimplemented as follows:

class BAdapter() implements I1
{
   void logA() { // nothing }
   void logB() { new BLogger().log() }
   void logC() { // nothing }
}

I would like to write a JUnit test that checks functionality, but I found this a bit problematic, since I cannot enter my Mock object instead BLoggeror check the return value. I found several possible solutions, but I'm not sure which is better.

Case 1: Add void setLogger(Logger l)to the class BAdapter.

class BAdapter() implements I1
{
   private Logger logger = new BLogger();

   public void logB() { logger.log() }
   public void setLogger(Logger l) { logger = l }
   .. //rest of methods
}

Cons: Why add a setter that is never used in "real", non-testing code?

Option Two: Add a protected factory method and subclass BAdapterto the test package.

class BAdapter() implements I1
{
   public void logB() { createLogger().log() }
   protected Logger createLogger() { retrun new BLogger() }
   .. //rest of methods
}

class BAdapterForTesting extends BAdapter()
{
   protected Logger createLogger() { retrun new MockBLogger() }
}

Cons: I'm not sure if this is a clean and elegant solution, but I do not see many shortcomings here.

: factory.

class BAdapter() implements I1
{
   public void logB() { AbstractFactory.getFactory().getBLogger().log() }
   .. //rest of methods
}

- :

AbstractFactory.setFactory(new MockLoggersFactory())

: , ?

: Boolean, , . .

class BAdapter() implements I1
{
   Boolean logA() { return false; }
   Boolean logB() { return new BLogger().log() }
   Boolean logC() { return false; }
}

: wowkaround. , "", ?

? - ?

+5
2

, , Case One , "" .

, , , . logB BLogger , . , Logger, , .

+2

IMVHO, , , , , , , .

3, , , , , .

, ​​ PowerMock, :

class BAdapter() implements I1
{
   private Logger logger = new BLogger();

   public void logB() { logger.log() }
   .. //rest of methods
}

:

Whitebox.setInternalState(loggerInstance, "logger", new MockLogger());

: http://code.google.com/p/powermock/wiki/BypassEncapsulation

, .

0

All Articles