【发布时间】:2022-10-23 12:08:50
【问题描述】:
我正在尝试在 Java 中正确模拟这个标志客户端,但我不知道该怎么做。通常,我会通过 WireMock 模拟第三方 API(模拟调用),它会帮助我模拟它并为其添加测试。但是,实际的调用和逻辑被隐藏在这个客户端对象下,我不确定我是否正确地模拟了它。
以下是文档中的一些代码:https://docs.flagsmith.com/clients/server-side#initialise-the-sdk
我现在在我的代码库中有这个设置:
执行:
@Gateway
public class FlagsmithGateway implements FlagsmithPort {
private final FlagsmithClient flagsmithClient;
@Autowired
public FlagsmithGateway(@Value("${flagsmith.environment.id}") String flagsmithEnvironmentId,
@Value("${flagsmith.endpoint}") String flagsmithEndpoint) {
this(FlagsmithClient
.newBuilder()
.setApiKey(flagsmithEnvironmentId)
.withApiUrl(flagsmithEndpoint)
.build());
}
public FlagsmithGateway(FlagsmithClient flagsmithClient) {
this.flagsmithClient = flagsmithClient;
}
@Override
public boolean isEnabled(FeatureFlags flag) throws FlagsmithClientError {
Flags flags = flagsmithClient.getEnvironmentFlags();
return flags.isFeatureEnabled(flag.toString());
}
@Override
public boolean isDisabled(FeatureFlags flag) throws FlagsmithClientError {
Flags flags = flagsmithClient.getEnvironmentFlags();
return !flags.isFeatureEnabled(flag.toString());
}
}
上面实现的测试类:
@ExtendWith(MockitoExtension.class)
public class FlagsmithGatewayTest {
private FlagsmithGateway flagsmithGateway;
@Mock
private FlagsmithClient flagsmithClient;
@BeforeEach
public void setup() {
flagsmithGateway = new FlagsmithGateway(flagsmithClient);
}
@Test
public void isEnabled_shouldReturnWhetherFeatureIsEnabled() throws FlagsmithClientError {
flagsmithClient = mock(FlagsmithClient.class);
Flags flags = setupFlags("test_toggle", true);
when(flagsmithClient.getEnvironmentFlags()).thenReturn(flags);=
boolean result = flagsmithGateway.isEnabled(FeatureFlags.TOGGLE_FOR_TESTS); //FlagsmithGateway is now null
assertThat(result).isTrue();
}
private static Flags setupFlags(String featureName, Boolean enabled) {
Flags flag = new Flags();
BaseFlag baseFlag = new BaseFlag();
Map<String, BaseFlag> someFlags = new HashMap<>();
baseFlag.setFeatureName(featureName);
baseFlag.setEnabled(enabled);
someFlags.put(featureName,baseFlag);
flag.setFlags(someFlags);
return flag;
}
}
虽然上面的代码通过了,但它实际上并没有测试网关。我尝试通过从网关代码调用该方法进行测试,但我遇到了模拟该行或 NPE 的问题。我如何正确测试这个标志客户端?谢谢!
【问题讨论】:
标签: java spring-boot unit-testing mocking mockito