So I have this extracted piece of code that tests CarFactory using a carMock. makeCar is a static method. (method/variable names and concepts etc. have been changed).
//imports here
public class Test
{
CarFactory carFactory;
BluePrint bp;
@BeforeEach
public void setup()
{
carFactory = new CarFactory();
bp = new BluePrint("toyota");
}
@Test
public void addCar()
{
// mock car
Car carMock = mock(Car.class);
try(MockedStatic<Car> mock = mockStatic(Car.class))
{
// makeCar is a static method
mock.when(() -> Car.makeCar(anyString(), anyInt()))
.thenThrow(new IllegalStateException());
// no blueprint
assertThrows(IllegalStateException.class, () ->
carFactory.addCar("toyota", 2000));
// add blueprint
carFactory.addBluePrint(bp);
// test addCar invalid parameters
mock.when(() -> Car.makeCar(anyString(), anyInt()))
.thenThrow(new IllegalArgumentException());
// quantity must be < 1000
assertThrows(IllegalArgumentException.class, () ->
carFactory.addCar("toyota", 15));
// no 'nissan' blueprint
assertThrows(IllegalArgumentException.class, () ->
carFactory.addCar("nissan", 10000));
mock.when(() -> Car.makeCar(anyString(), anyInt()))
.thenReturn(carMock);
// should work
Car c = carFactory.addCar("toyota", 10000);
assertEquals(c, carMock);
}
}
}
My tests compile fine on my pc, but on my tutor's, they give 2 errors:
- "error: class, interface, enum, or record expected" for mock.when() and assertThrows() lines.
- "error: expected" for the assertThrows() lines.
Is it to do with putting code in the mockedStatic try block?