Skip to content

Instantly share code, notes, and snippets.

@nielsutrecht
Created November 23, 2017 07:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nielsutrecht/150ad8c070d5cbaadf53a2183763f4e1 to your computer and use it in GitHub Desktop.
Save nielsutrecht/150ad8c070d5cbaadf53a2183763f4e1 to your computer and use it in GitHub Desktop.
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");
}
}
}
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