简体   繁体   中英

Run code only on test

I would like to execute a method only on test running.

This is a completion of integration test. When I run integration test, I want to generate a json file with the state of an Object.

I think of doing something like this in my code :

if(environnement == TEST) {
   // save object as json
}

Do you know other method to do this ? less crapy ?

Regards

How about using the Polymorphism OOP feature?

abstract class MyObject {
    void doSomething();
}

class MyObjectImpl {
    void doSomething() {
        // real implementation
    }
}

class MyObjectTest {
    void doSomething() {
        // create your json or other test functional
    }
}

class MyObjectFactory {
    static getMyObject(Environment env) {
        if (env == Environment.TEST) {
            return new MyObjectTest();
        } else {
            return new MyObjectImpl();
        }
    }
}

I generally provide test 'hooks' using this pattern

public class MyObject {

    public void doStuff() {
        // stuff to do

        onCompleteStuff();
    }

    protected void onCompleteStuff() {
    }
}

Then in the test code you can create a subclass of MyObject that does your test-only actions:

private MyObject newMyObject() {
 return new MyObject() {
   @Override
   protected void onCompleteStuff() {
       saveObjectAsJson();
   }
 };
}

This has the advantage of keeping test code out of your main build. It will also work if you must use a mock in your tests. For example, using the excellent Mockito library:

MyObject foo=Mockito.spy(new MyObject());

doAnswer(new Answer<Object>() {
  @Override
  public Object answer(InvocationOnMock invocation) throws Throwable {
    saveObjectToJson();
    return null;
  }
}).when(foo).onCompleteStuff();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM