Created
November 23, 2017 07:41
-
-
Save nielsutrecht/150ad8c070d5cbaadf53a2183763f4e1 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ioc; | |
public class Car { | |
private final Engine engine; | |
private int fuel; | |
public Car(Engine engine) { | |
this.engine = engine; | |
} | |
public void addFuel(int fuel) { | |
if(fuel < 0) { | |
throw new IllegalArgumentException("Can't add negative fuel"); | |
} | |
this.fuel += fuel; | |
} | |
public void start() { | |
if(fuel <= 0) { | |
throw new RuntimeException("Empty tank!"); | |
} | |
engine.start(); | |
} | |
public static class Engine { | |
public void start() { | |
System.out.println("Engine start"); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package ioc; | |
import org.junit.Before; | |
import org.junit.Rule; | |
import org.junit.Test; | |
import org.junit.rules.ExpectedException; | |
import org.mockito.Mockito; | |
public class CarTest { | |
private Car.Engine mockEngine; | |
private Car car; | |
@Rule | |
public ExpectedException expectedException = ExpectedException.none(); | |
@Before | |
public void setup() { | |
mockEngine = Mockito.mock(Car.Engine.class); | |
car = new Car(mockEngine); | |
} | |
@Test | |
public void addFuel_NotNegative() throws Exception { | |
expectedException.expect(IllegalArgumentException.class); | |
expectedException.expectMessage("Can't add negative fuel"); | |
car.addFuel(-1); | |
} | |
@Test | |
public void start_NoFuel() throws Exception { | |
expectedException.expect(RuntimeException.class); | |
expectedException.expectMessage("Empty tank!"); | |
car.start(); | |
} | |
@Test | |
public void start() throws Exception { | |
car.addFuel(10); | |
car.start(); | |
Mockito.verify(mockEngine).start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment