0

经过一番调查,我继续寻求一种更直观的方式来模拟 Mutiny.Session 并测试我的功能。

这是我要测试的方法:

public class ServiceCrud {

    @Inject
    Mutiny.SessionFactory mutinySessionFactory;

    @Inject
    MicroserviceService service;

    public Uni<Service> get(@NotNull final String identifier) throws ConstraintViolationException, NotFoundException {
        return mutinySessionFactory.withSession(session -> {
            EntityGraph<Service> entityGraph = session.getEntityGraph(Service.class, "exampleEntityGraph");

            return service.get(identifier)
                .onItem().ifNull().failWith(NotFoundException::new)
                .onItem().transformToUni(
                    microservice -> Uni.createFrom()
                        .item(new Service(microservice.getMsId(), microservice.getMsName())));
        });
    }
}

我发现测试的唯一方法是通过参数捕获器:

@ExtendWith(MockitoExtension.class)
public class ServiceCrudTest {

    @InjectMocks
    private ServiceCrud serviceCrud;

    @Mock
    Mutiny.SessionFactory mutinySessionFactory;

    @Mock
    MicroserviceService service;

    @Captor
    ArgumentCaptor<Function<Session, Uni<Service>>> captor;

    @Mock
    Session session;

    @Mock
    EntityGraph<Service> entityGraph;

    @Test
    void getTest() {
        // data
        String msId = "msid";
        String msName = "name";
        
        Microservice toBeReturned = new Microservice();
        toBeReturned.setMsId(msId);
        toBeReturned.setMsName(msName);
        
        Service expected = new Service();
        expected.setId(msId);
        expected.setName(msName);

        // expectation
        doReturn(Uni.createFrom().item(toBeReturned))
            .when(service).get(anyString());
        doReturn(entityGraph).when(session)
            .getEntityGraph(Mockito.eq(Service.class), Mockito.anyString());

        // action
        serviceCrud.get("");
        
        // capture the function and invoke it
        Mockito.verify(mutinySessionFactory).withSession(captor.capture());
        Function<Session, Uni<Service>> value = captor.getValue();
        Uni<Service> callback = value.apply(session);
        
        UniAssertSubscriber<Service> subscriber = callback
                .subscribe().withSubscriber(UniAssertSubscriber.create());
        subscriber.assertCompleted().assertItem(expected);
    }
}

这是唯一的测试方法吗?这是正确的测试方法吗?

任何提示将不胜感激

4

0 回答 0