Menu

JPDBC in nutshell

Main features

  • no need to use preprocessors or java-agents
  • primary target in unit/component tests
  • contracts are defined with annotations: @Invariant, @Pre, @Post
  • contracts are evaluated using reflection and JavaScript engine
  • contracts can be evaluated for mock-objects

Simple example 1/2

In the following example MyManager uses interface MyInterface, but the implementor of MyManager has not honoured the contract @Pre("!=null"). (Fix for this could be e.g. using Google Guava's Strings.nullToEmpty in the callDo)

(Imports are not showed in the following snippets to save vertical space)

MyInterface.java :

public interface MyInterface {
    @Post("result == 'success' || result == 'failure'")
    String doIt(@Pre("!=null") String text);
}

MyManager.java :

public class MyManager {
    private final MyInterface myInterface;
    public MyManager(MyInterface myInterface) {
        this.myInterface = myInterface;
    }
    public void callDo(String text) {
        myInterface.doIt(text);
    }
}

MyManagerTest.java :

public class MyManagerTest extends EasyMockSupportWithDbC {
    @Test
    public void test() {
        MyInterface myInterface = createNiceMock(MyInterface.class);
        MyManager myManager = new MyManager(myInterface);
        replayAll();
        myManager.callDo(null);  // this will throw PreconditionException
        verifyAll();
    }
}

Simple example 2/2

Also the implementor of MyInterface has been lazy, and has not honoured the postcondition @Post("result == 'success' || result == 'failure'").

MyObject.java :

public class MyObject implements MyInterface {
    @Override
    public String doIt(String text) {
        if (text.equals("password")) {
            return "success";
        }
        return "";
    }
}

MyObjectTest.java :

public class MyObjectTest extends EasyMockSupportWithDbC {
    @Test
    public void test() {
        MyObject myObject = dbc(new MyObject());
        myObject.doIt("password");
        myObject.doIt("teststring");
    }
}
Posted by Jari-Pekka Ryynänen 2013-09-30 | Draft

Log in to post a comment.

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.