'Error with junit mocking with MockedStatic
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?
Solution 1:[1]
I have a hunch it's to do with this line, since my other tests that don't have a line like this aren't having errors:
mock.when(() -> Car.makeCar(anyString(), anyInt()))
.thenThrow(new IllegalStateException());
Correct me if I'm wrong, but you cannot use thenThrow in place of thenReturn.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Kit oh |
