

Unit Testing as the name implies asks you to test a Class (Unit) in isolation.



If your code mixes Object Construction with Logic you will never be able to achieve isolation.



In order to unit-test you need to separate object graph construction from the application logic into two different classes



The end goal is to have either: classes with logic OR classes with " new " operators.

House

JUnit

House

class House {

private boolean isLocked;

private boolean isLocked() {

return isLocked;

}

private boolean lock() {





isLocked = true;



}

}

class House {

private final Kitchen kitchen = new Kitchen();

private boolean isLocked;

private boolean isLocked() {

return isLocked;

}

private boolean lock() {





kitchen.lock();



isLocked = true;



}

}

House

House

Kitchen

new

Kitchen

House

Kitchen

House

Kitchen

House

class House {

private final Kitchen kitchen;



private boolean isLocked;

public House(Kitchen kitchen) {

this.kitchen = kitchen;

}

private boolean isLocked() {

return isLocked;

}

private boolean lock() {





kitchen.lock();



isLocked = true;



}

}

new

new

House

Kitchen

House

new

new

class ApplicationBuilder {

House build() {

return new House(

new Kitchen(new Sink(), new Dishwasher(), new Refrigerator())

);

}

}

ApplicationBuilder

class Main {

public static void(String...args) {

House house = new ApplicationBuilder().build();

house.lock();

}

}

new