B
B
Biaci_Anj2022-04-18 01:45:00
Java
Biaci_Anj, 2022-04-18 01:45:00

Mockito inline

Here is an example of a super simplified testable class.

public class DishService {

    DaoFactory daoFactory = DaoFactory.getInstance();

    public void exampleMethod() {
        System.out.println(daoFactory);
     DishDao dishDao = daoFactory.createDishDao();
        System.out.println(dishDao.findById(1));
    }
}

Here is DaoFactory

public abstract class DaoFactory {
    private static DaoFactory daoFactory;
    public abstract UserDao createUserDao();
    public abstract DishDao createDishDao();
    public abstract OrderDao createOrderDao();

    public static DaoFactory getInstance() {
        if (daoFactory == null) {
            synchronized (DaoFactory.class) {
                daoFactory = new JDBCDaoFactory();

            }
        }
        return daoFactory;
    }
}

Here is my test class
@ExtendWith(MockitoExtension.class)
     class DishServiceTest {
        @Spy
        DishService dishService;
        @Mock
        DishDao dishDao;
        @Mock
        DaoFactory daoFactory;
    
        @Test
        void example() {
            MockedStatic<DaoFactory> daoFactoryDummy = Mockito.mockStatic(DaoFactory.class);
            daoFactoryDummy.when(DaoFactory::getInstance).thenReturn(daoFactory);
            Mockito.when(daoFactory.createDishDao()).thenReturn(dishDao);
            when(dishDao.findById(1)).thenReturn(new Dish());
            dishService.exampleMethod();
        }

The problem is that daoFactory does not get wet, as you can see, I return an empty dish, but in the console I see this.
This means that the mocking is not working and I am connecting to the real DishFacotry.

Dish{name='dadawd', description='wdadwad2', category=DRINKS, price=23131.00, imageFileName='FIRSTSnacksAsDaypart_1.jpg', orderItems=null}

Unnecessary stubbings detected.
1. -> at service.DishServiceTest.example(DishServiceTest.java:35)
2. -> at service.DishServiceTest.example(DishServiceTest.java:36) 35 and 36 lines of code you can see at the screen.

Here are 35 and 36 lines of code
9u8a0.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question