Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 模拟类和接口_Java_Unit Testing_Interface_Mockito - Fatal编程技术网

Java 模拟类和接口

Java 模拟类和接口,java,unit-testing,interface,mockito,Java,Unit Testing,Interface,Mockito,大家好,到目前为止,我一直在尝试在测试中使用mockito。 这是我的问题:我能模拟一个接口吗?这样实现这个接口的每个类的行为都会像模拟中描述的那样 这是我正在测试的方法: public static boolean initNewCluster(ServerConfiguration conf) throws Exception { return runFunctionWithRegistrationManager(conf, rm -> { try {

大家好,到目前为止,我一直在尝试在测试中使用mockito。 这是我的问题:我能模拟一个接口吗?这样实现这个接口的每个类的行为都会像模拟中描述的那样

这是我正在测试的方法:

public static boolean initNewCluster(ServerConfiguration conf) throws Exception {
    return runFunctionWithRegistrationManager(conf, rm -> {
        try {
            return rm.initNewCluster();
        } catch (Exception e) {
            System.out.println("MOCK WORKS!!! \n");
            throw new UncheckedExecutionException(e.getMessage(), e);
        }
    });
}
我需要模拟调用rm.initNewCluster()。 现在,这是将initNewCluster()作为方法的接口:

@LimitedPrivate
@Evolving
public interface RegistrationManager extends AutoCloseable {

    

    /**
     * Initializes new cluster by creating required znodes for the cluster. If
     * ledgersrootpath is already existing then it will error out.
     *
     * @return returns true if new cluster is successfully created or false if it failed to initialize.
     * @throws Exception
     */

    boolean initNewCluster() throws Exception;
下面是实现此接口的类:

    /**
     * ZooKeeper Based {@link RegistrationManager}.
     */
    @Slf4j
    public class ZKRegistrationManager implements RegistrationManager {
    
        private static final Function<Throwable, BKException> EXCEPTION_FUNC = cause -> {
            if (cause instanceof BKException) {
                log.error("Failed to get bookie list : ", cause);
                return (BKException) cause;
            } else if (cause instanceof InterruptedException) {
                log.error("Interrupted reading bookie list : ", cause);
                return new BKInterruptedException();
            } else {
                return new MetaStoreException();
            }
        };
    
        private final ServerConfiguration conf;
        private final ZooKeeper zk;
        private final List<ACL> zkAcls;
        private final LayoutManager layoutManager;
    
        private volatile boolean zkRegManagerInitialized = false;
    
        // ledgers root path
        private final String ledgersRootPath;
        // cookie path
        private final String cookiePath;
        // registration paths
        protected final String bookieRegistrationPath;
        protected final String bookieReadonlyRegistrationPath;
        // session timeout in milliseconds
        private final int zkTimeoutMs;
    
        public ZKRegistrationManager(ServerConfiguration conf,
                                     ZooKeeper zk,
                                     RegistrationListener listener) {
            this(conf, zk, ZKMetadataDriverBase.resolveZkLedgersRootPath(conf), listener);
        }
    
        public ZKRegistrationManager(ServerConfiguration conf,
                                     ZooKeeper zk,
                                     String ledgersRootPath,
                                     RegistrationListener listener) {
            this.conf = conf;
            this.zk = zk;
            this.zkAcls = ZkUtils.getACLs(conf);
            this.ledgersRootPath = ledgersRootPath;
            this.cookiePath = ledgersRootPath + "/" + COOKIE_NODE;
            this.bookieRegistrationPath = ledgersRootPath + "/" + AVAILABLE_NODE;
            this.bookieReadonlyRegistrationPath = this.bookieRegistrationPath + "/" + READONLY;
            this.zkTimeoutMs = conf.getZkTimeout();
    
            this.layoutManager = new ZkLayoutManager(
                zk,
                ledgersRootPath,
                zkAcls);
    
            this.zk.register(event -> {
                if (!zkRegManagerInitialized) {
                    // do nothing until first registration
                    return;
                }
                // Check for expired connection.
                if (event.getType().equals(EventType.None)
                    && event.getState().equals(KeeperState.Expired)) {
                    listener.onRegistrationExpired();
                }
            });
        }
    
.
.
.
.
.
.
    
    
       
    
        @Override
        public boolean initNewCluster() throws Exception {
            System.out.println("I have been called ! \n");
            String zkServers = ZKMetadataDriverBase.resolveZkServers(conf);
            String instanceIdPath = ledgersRootPath + "/" + INSTANCEID;
            log.info("Initializing ZooKeeper metadata for new cluster, ZKServers: {} ledger root path: {}", zkServers,
                    ledgersRootPath);
    
            boolean ledgerRootExists = null != zk.exists(ledgersRootPath, false);
    
            if (ledgerRootExists) {
                log.error("Ledger root path: {} already exists", ledgersRootPath);
                return false;
            }
    
            List<Op> multiOps = Lists.newArrayListWithExpectedSize(4);
    
            // Create ledgers root node
            multiOps.add(Op.create(ledgersRootPath, EMPTY_BYTE_ARRAY, zkAcls, CreateMode.PERSISTENT));
    
            // create available bookies node
            multiOps.add(Op.create(bookieRegistrationPath, EMPTY_BYTE_ARRAY, zkAcls, CreateMode.PERSISTENT));
    
            // create readonly bookies node
            multiOps.add(Op.create(
                bookieReadonlyRegistrationPath,
                EMPTY_BYTE_ARRAY,
                zkAcls,
                CreateMode.PERSISTENT));
    
            // create INSTANCEID
            String instanceId = UUID.randomUUID().toString();
            multiOps.add(Op.create(instanceIdPath, instanceId.getBytes(UTF_8),
                    zkAcls, CreateMode.PERSISTENT));
    
            // execute the multi ops
            zk.multi(multiOps);
    
            // creates the new layout and stores in zookeeper
            AbstractZkLedgerManagerFactory.newLedgerManagerFactory(conf, layoutManager);
    
            log.info("Successfully initiated cluster. ZKServers: {} ledger root path: {} instanceId: {}", zkServers,
                    ledgersRootPath, instanceId);
            return true;
        }
    
        
    }
/**
*基于ZooKeeper的{@link RegistrationManager}。
*/
@Slf4j
公共类ZKRegistrationManager实现RegistrationManager{
私有静态最终函数异常\u FUNC=原因->{
如果(导致BKException实例){
log.error(“无法获取赌注列表:”,原因);
返回(异常)原因;
}否则如果(导致中断异常的实例){
日志错误(“中断读取赌注列表:”,原因);
返回新的BKInterruptedException();
}否则{
返回新的MetaStoreException();
}
};
私有最终服务器配置配置;
私人最终动物园管理员zk;
私人最终名单;
私人最终布局经理布局经理;
私有易失性布尔值zkRegManagerInitialized=false;
//分类账根路径
私有最终字符串分类账根路径;
//cookie路径
私有最终字符串路径;
//注册路径
受保护的最终字符串BookierRegistrationPath;
受保护的最终字符串BookierReadOnlyRegistrationPath;
//会话超时(毫秒)
私人终场暂停;
公共ZKRegistrationManager(服务器配置配置,
动物园管理员zk,
注册侦听器(侦听器){
这是(conf,zk,zkmatadriverbase.resolvezklegrsrootpath(conf),listener);
}
公共ZKRegistrationManager(服务器配置配置,
动物园管理员zk,
字符串ledgersRootPath,
注册侦听器(侦听器){
this.conf=conf;
this.zk=zk;
this.zkals=ZkUtils.getACLs(conf);
this.ledgersRootPath=ledgersRootPath;
this.cookiePath=ledgersRootPath+“/”+COOKIE\u节点;
this.bookierRegistrationPath=LedgerRootPath+“/”+可用\u节点;
this.BookierReadOnlyRegistrationPath=this.BookierRegistrationPath+“/”+只读;
this.zkTimeoutMs=conf.getZkTimeout();
this.layoutManager=new ZkLayoutManager(
zk,
根路径,
zkAcls);
此.zk.register(事件->{
如果(!zkRegManagerInitialized){
//在第一次注册之前不要做任何事情
返回;
}
//检查连接是否过期。
if(event.getType().equals(EventType.None)
&&event.getState().equals(KeeperState.Expired)){
listener.onRegistrationExpired();
}
});
}
.
.
.
.
.
.
@凌驾
公共布尔initNewCluster()引发异常{
System.out.println(“我被叫了!\n”);
字符串zkServers=zkmatadriverbase.resolveZkServers(conf);
字符串instanceIdPath=LedgerRootPath+“/”+INSTANCEID;
info(“初始化新集群的ZooKeeper元数据,ZKServers:{}账本根路径:{}”,ZKServers,
分类账(根路径);
布尔值ledgerRootExists=null!=zk.exists(ledgersRootPath,false);
如果(ledgerRootExists){
错误(“账本根路径:{}已存在”,账本根路径);
返回false;
}
List multiOps=Lists.newArrayListWithExpectedSize(4);
//创建分类账根节点
add(Op.create(ledgersRootPath,空字节数组,zkAcls,CreateMode.PERSISTENT));
//“创建可用的赌注”节点
add(Op.create(bookierregistrationpath,空字节数组,zkAcls,CreateMode.PERSISTENT));
//“创建只读赌注”节点
multiOps.add(Op.create(
BookierReadOnlyRegistrationPath,
空字节数组,
zkAcls,
CreateMode.PERSISTENT);
//创建实例ID
字符串instanceId=UUID.randomUUID().toString();
multiOps.add(Op.create(instanceIdPath,instanceId.getBytes,UTF_8),
zkAcls,CreateMode.PERSISTENT));
//执行多重操作
zk.multi(multiOps);
//创建新布局并存储在zookeeper中
NewLedgerManager工厂(conf,layoutManager);
log.info(“已成功启动cluster.ZKServers:{}账本根路径:{}实例ID:{}”,ZKServers,
账本根路径,实例ID);
返回true;
}
}
这是我的测试课:

package org.apache.bookkeeper.client;


import org.apache.bookkeeper.conf.ServerConfiguration;
import org.apache.bookkeeper.discover.RegistrationManager;
import org.apache.bookkeeper.discover.ZKRegistrationManager;
import org.apache.bookkeeper.meta.LayoutManager;
import org.apache.bookkeeper.test.BookKeeperClusterTestCase;
import org.apache.bookkeeper.test.ZooKeeperCluster;
import org.apache.bookkeeper.test.ZooKeeperUtil;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.mockito.InjectMocks;
import org.mockito.Mock;



import java.util.Arrays;
import java.util.Collection;
import java.util.List;

import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;


@RunWith(value= Parameterized.class)
public class BookKeeperAdminInitNewClusterTest extends BookKeeperClusterTestCase {

    private boolean result;
    private ServerConfiguration conf;
    private String confType ;

    private static final int numOfBookies = 2;
    private final int lostBookieRecoveryDelayInitValue = 1800;


    @Mock
    RegistrationManager mockedRM = mock(RegistrationManager.class) ;
  


    @Parameterized.Parameters
    public static Collection<Object[]> getTestParameters(){
        return Arrays.asList(new Object[][]{

                //last parameter states if the method rm.initNewCluster() called inside
                // BookKeeperAdmin.initNewCluster(conf) must be mocked or not

                //{true ,  "new" },
                //{false , "null" },
                //{false , "wrong"},
                {false , "mock"},  //caso di test introdotto per portare la branch coverage al 100%
                                    // entrando nella clausola catch del metodo initNewCluste()

        });

    }



    public BookKeeperAdminInitNewClusterTest(boolean result , String conf) throws Exception {

        super(numOfBookies, 480);
        baseConf.setLostBookieRecoveryDelay(lostBookieRecoveryDelayInitValue);
        baseConf.setOpenLedgerRereplicationGracePeriod(String.valueOf(30000));
        setAutoRecoveryEnabled(true);

        this.result = result;
        this.confType = conf;


    }

    @Test
    public void testInitNewCluster() throws Exception {

        boolean realResult ;


        if(confType == "null"){

            this.conf = null;

        }else if( confType == "wrong"){

            this.conf = new ServerConfiguration().setMetadataServiceUri("zk+hierarchical://127.0.0.1/ledgers");

        }else if(confType == "new") {

            this.conf = new ServerConfiguration(baseConf);
            String ledgersRootPath = "/testledgers";
            this.conf.setMetadataServiceUri(newMetadataServiceUri(ledgersRootPath));

        }else if(confType == "mock"){



            this.conf = new ServerConfiguration(baseConf);
            String ledgersRootPath = "/testledgers";
            this.conf.setMetadataServiceUri(newMetadataServiceUri(ledgersRootPath));
   

            when(mockedRM.initNewCluster()).thenThrow(new Exception());



        }


        try {

            realResult = BookKeeperAdmin.initNewCluster(conf);

        } catch (Exception e) {
            realResult = false ;
            e.printStackTrace();

        }
        assertEquals(result,realResult);
    }

}`
package org.apache.bookkeeper.client;
导入org.apache.bookkeeper.conf.ServerConfiguration;
导入org.apache.bookkeeper.discover.RegistrationManager;
导入org.apache.bookkeeper.discover.ZKRegistrationManager;
导入org.apache.bookkeeper.meta.LayoutManager;
导入org.apache.bookkeeper.test.BookKeeperClusterTestCase;
导入org.apache.bookkeeper.test.ZooKeeperCluster;
导入org.apache.bookocker.test.ZooKeeperUtil;
导入org.apache.zookeeper.zookeeper;
导入org.apache.zookeeper.data.ACL;
导入org.junit.Test;
导入org.junit.runner.RunWith;
进口