我正在使用JUnit
为Mockito
写一个具有以下条件的方法:
if(curatorFramework.getZooKeeperClient().isConnected() {
//do something
}
我必须测试做一些事情。为此,我试图模拟IF条件为真。我在下面尝试过:
@Mock CuratorFramework curatorFrameworkMock
when(curatorFrameworkMock.getZooKeeperClient().isConnected()).thenReturn(true);
但它会抛出NullPointerException
,因为
curatorFrameworkMock.getZooKeeperClient() expects ZooKeeperClient Object to call isConnected().
我无法在ZooKeeperClient
课程中创建JUnit
的对象。如何通过Mocking将此IF条件设置为TRUE?
答案 0 :(得分:2)
只需为CuratorZookeeperClient
创建一个模拟对象,并让该对象模拟isConnected
的响应。
CuratorZookeeperClient curatorZookeeperClientMock = Mockito.mock(CuratorZookeeperClient.class);
when(curatorZookeeperClientMock.isConnected()).thenReturn(true);
CuratorFramework curatorFrameworkMock = Mockito.mock(CuratorFramework.class);
when(curatorFrameworkMock.getZookeeperClient()).thenReturn(curatorZookeeperClientMock);
答案 1 :(得分:0)
这可能比你希望的更加冗长,但这是我们正在使用的测试。 Mock用于模拟策展人数据,我们希望检索Camel路由所需的Kafka服务器的IP。
@Test
public void testURIExtraction() throws Exception
{
//Create a mock curator to return mock kafka IP data
ExistsBuilder existsBuilder = Mockito.mock(ExistsBuilder.class);
when(existsBuilder.forPath(KAFKA_BASE_PATH)).thenReturn(new Stat());
GetDataBuilder getDataBuilder = Mockito.mock(GetDataBuilder.class);
when(getDataBuilder.forPath(KAFKA_BASE_PATH)).thenReturn(_createMockData());
CuratorFramework curatorFramework = Mockito.mock(CuratorFramework.class);
when(curatorFramework.checkExists()).thenReturn(existsBuilder);
when(curatorFramework.getData()).thenReturn(getDataBuilder);
//create a kafkaURIExtractor object and generate the trafficeEventEndpointURI
KafkaURIExtractor kafkaURIExtractor = new KafkaURIExtractor();
kafkaURIExtractor.setBasePath(KAFKA_BASE_PATH);
kafkaURIExtractor.setKafkaZKPort("2181");
kafkaURIExtractor.setCurator(curatorFramework);
kafkaURIExtractor.init();
String trafficEventEndpoint = kafkaURIExtractor.getTrafficEventEndpointURI();
Assert.assertEquals(EXPECTED_RESULT, trafficEventEndpoint);
}
private byte[] _createMockData() throws JSONException
{
JSONArray data = new JSONArray();
JSONObject location = new JSONObject();
JSONArray ips = new JSONArray();
ips.put("127.0.0.1");
location.put("cluster", "test-mojave_dev");
location.put("ips", ips);
data.put(location);
return data.toString().getBytes();
}
在方法调用嵌套的意义上,它类似于您的示例。 I.E.为了调用curatorFramework.getData().forPath(...)
,我们必须首先通过返回预期类型的模拟对象来解决curatorFramework.getData()
,在这种情况下是GetDataBuilder.class
KafkaURIExtractor
对象只检查策展人上是否存在KAFKA_BASE_PATH,然后检索并格式化数据,然后返回getTrafiicEventEndpointURI()