mockito 未在静态方法上启动模拟

yzxexxkh  于 2022-11-08  发布在  其他
关注(0)|答案(1)|浏览(146)

我在模拟静态方法时遇到了一些问题。下面是我调用静态方法的代码

public class GetAllBatches {
    public HttpResponseMessage run(
            @HttpTrigger(route = "v1/batches",
                    name = "request",
                    methods = {HttpMethod.GET},
                    authLevel = AuthorizationLevel.ANONYMOUS)
                    HttpRequestMessage<String> request,
            final ExecutionContext context){
        context.getLogger().info("List batches Called");
        String apiResponse ;
        String connector = request.getQueryParameters().getOrDefault("connector", "");
        try{
            BatchesController batchesController = BatchesController.getInstance();
            apiResponse = new Gson().toJson(batchesController.getBatches(connector));
        }
    }
}

批次控制器类别:

public class BatchesController {

    Logger log = Logger.getLogger(BatchesController.class.getName());

    public static BatchesController getInstance() {
        if (batchesController == null) {
            batchesController = new BatchesController(BatchDaoFactory.getDao());
        }
        return batchesController;
    }

    private static BatchesController batchesController = new BatchesController();
    private final BatchDao batchDao;

    public BatchesController(BatchDao BatchDao) {
        this.batchDao = BatchDao;
    }
// Do something
}

下面是我的测试:

@RunWith(MockitoJUnitRunner.class)
public class GetAllBatchesTest {
    @Mock
    ExecutionContext context;
    @Mock
    HttpRequestMessage<String> request;
    @Mock
    BatchesController batchesController;
    @Mock
    BatchDao BatchDao;

    @InjectMocks
    GetAllBatches getAllBatchesMock = new GetAllBatches();

    @Before
    public void setUp()  {
        Map<String, String> map = new HashMap<>();
        map.put("connector", "");

        doReturn(Logger.getGlobal()).when(context).getLogger();
        doReturn(map).when(request).getQueryParameters();
        try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
            utilities.when(BatchesController::getInstance).thenReturn(batchesController);
        }
        doAnswer((Answer<HttpResponseMessage.Builder>) invocationOnMock -> {
            HttpStatus status = (HttpStatus) invocationOnMock.getArguments()[0];
            return new HttpResponseMessageMock.HttpResponseMessageBuilderMock().status(status);
        }).when(request).createResponseBuilder(any(HttpStatus.class));
    }

    @Test
    public void testHttpTriggerJava()  {

        final HttpResponseMessage ret = getAllBatchesMock.run(request, context);
        Assertions.assertEquals(ret.getStatus(), HttpStatus.OK);
    }

当我运行测试时,它抛出一条错误消息:初始化器中出现异常错误
getInstance()实际上并没有返回模拟值。
我不知道这里出了什么问题?
UPDATE:我发现问题是因为我使用了Mockito-inline Mockito-inline无法在类上初始化mock,但只能在接口上初始化mock

icnyk63a

icnyk63a1#

您正在使用try-with-resources块来设置静态模拟:

try (MockedStatic<BatchesController> utilities = Mockito.mockStatic(BatchesController.class)) {
    utilities.when(BatchesController::getInstance).thenReturn(batchesController);
}

请记住,静态模拟只在块的范围内是活动的--退出块后,资源将关闭。
因此,您需要:

  • 将静态模拟初始化从setup方法移动到test方法
  • 运行try-with-resources块中的测试代码

相关问题