0

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:

  1. "error: class, interface, enum, or record expected" for mock.when() and assertThrows() lines.
  2. "error: expected" for the assertThrows() lines.

Is it to do with putting code in the mockedStatic try block?

Kit oh
  • 29
  • 1
  • 5
  • Check this it might help: https://stackoverflow.com/questions/14954322/powermock-mockito-does-not-throw-exception-when-told-to – Mayssara Omar Aug 08 '22 at 00:28

1 Answers1

0

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.

Kit oh
  • 29
  • 1
  • 5