gpt4 book ai didi

java - 带私有(private)类参数的方法的 JMockit MockUp

转载 作者:行者123 更新时间:2023-12-02 04:55:51 28 4
gpt4 key购买 nike

我正在使用 JUnit 和 JMockit 编写一些单元测试,并且需要为采用私有(private)枚举实例作为参数的方法编写 JMockit MockUp。这是我需要模拟的类:

public class Result {
//Static constants representing metrics
public static final Metric AVOIDABLE = Metric.avoidable;
public static final Metric UNAVOIDABLE = Metric.unavoidable;

// private enumeration of metric values
private enum Metric {avoidable, unavoidable};

public Long getTodayCount(Metric metric) { //<- instance of private enum
return getValueForKey(metric);
}
}

根据给定的特定Metric,我需要返回不同的Long值。如果 Metric 枚举是公开的,那就足够简单了。像这样的东西:

private static class MockResult extends MockUp<Result> {
@Mock
Long getTodayCount(Metric m){ //<-- nope. Metric is private
if(Result.AVOIDABLE.equals(m)){ //<-- can't call equals either
return 1234L;
} else {
return 4567L;
}
}
}

但是由于 Metric 是私有(private)的,除了将 Metric 更改为公开之外,还有其他方法可以实现此目的吗?这可能最终是实现这一目标的唯一方法,但我不是 Result 类的作者,并且不完全熟悉将 Metric 设为私有(private)的原因第一名。

最佳答案

根据文档:

The @Mock annotation marks those methods in the mock-up class which are meant to provide mock implementations for the corresponding methods (of the same signature) in the mocked class.

如果枚举是私有(private)的,则不能在单元测试中使用它,因为它在类之外不可见。那么你就无法定义正确的MockUp。

您必须使 Metric 类更加可见(至少是包私有(private)),或者模拟整个 Result 类。

关于java - 带私有(private)类参数的方法的 JMockit MockUp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28780950/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com