0

I want to test MessageProcessor1.listAllKeyword method, which in turn calls HbaseUtil1.getAllKeyword method. Initialy, I had to deal with a problem associated with the static initializer and the constructor. The problem was to initialize a HBASE DB connection. I used powerMock to suppress static and constructor calls and it worked fine.

Even though I mocked HbaseUtil1.getAllKeyword method, actual method is being called and executes all HBase code leading to an exception, in which HBASE server is not up. EasyMock.expect(hbaseUtil.getAllKeyword("msg", "u1")).andReturn(expectedList);

Please give me any idea on how to avoid an actual method call. I tried many ways but none of them worked.

public class MessageProcessor1 
{
    private static Logger logger = Logger.getLogger("MQ-Processor");
    private final static String CLASS_NAME = "MessageProcessor";
    private static boolean keywordsTableExists = false;
    public static PropertiesLoader props;
    HbaseUtil1 hbaseUtil;
    /**
     * For checking if table exists in HBase. If doesn't exists, will create a
     * new table. This runs only once when class is loaded.
     */
    static {
        props = new PropertiesLoader();
        String[] userTablefamilys = {
                props.getProperty(Constants.COLUMN_FAMILY_NAME_COMMON_KEYWORDS),
                props.getProperty(Constants.COLUMN_FAMILY_NAME_USER_KEYWORDS) };
        keywordsTableExists = new HbaseUtil()
        .creatTable(props.getProperty(Constants.HBASE_TABLE_NAME),
                userTablefamilys);
    }

    /**
     * This will load new configuration every time this class instantiated.
     */
    {
        props = new PropertiesLoader();
    }

    public String listAllKeyword(String userId) throws IOException {
        HbaseUtil1 util = new HbaseUtil1();
        Map<String, List<String>> projKeyMap = new HashMap<String, List<String>>();
        //logger.info(CLASS_NAME+": inside listAllKeyword method");
        //logger.debug("passed id : "+userId);
        List<String> qualifiers = util.getAllKeyword("msg", userId);

        List<String> keywords = null;
        for (String qualifier : qualifiers) {
            String[] token = qualifier.split(":");

            if (projKeyMap.containsKey(token[0])) {
                projKeyMap.get(token[0]).add(token[1]);
            } else {
                keywords = new ArrayList<String>();
                keywords.add(token[1]);
                projKeyMap.put(token[0], keywords);
            }
        }

        List<Project> projects = buildProject(projKeyMap);
        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation()
                .create();
        System.out.println("Json projects:::" + gson.toJson(projects));
        //logger.debug("list all keyword based on project::::"+ gson.toJson(projects));
        //return gson.toJson(projects);
        return "raj";
    }

    private List<Project> buildProject(Map<String, List<String>> projKeyMap) {

        List<Project> projects = new ArrayList<Project>();
        Project proj = null;
        Set<String> keySet = projKeyMap.keySet();
        for (String hKey : keySet) {
            proj = new Project(hKey, projKeyMap.get(hKey));
            projects.add(proj);

        }
        return projects;
    }

    //@Autowired
    //@Qualifier("hbaseUtil1")
    public void setHbaseUtil(HbaseUtil1 hbaseUtil) {
        this.hbaseUtil = hbaseUtil;
    }

}



public class HbaseUtil1 {

    private static Logger logger = Logger.getLogger("MQ-Processor");
    private final static String CLASS_NAME = "HbaseUtil";
    private static Configuration conf = null;

    public HbaseUtil1() {
        PropertiesLoader props = new PropertiesLoader();
        conf = HBaseConfiguration.create();
        conf.set(HConstants.ZOOKEEPER_QUORUM, props
                .getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM));
        conf.set(
                HConstants.ZOOKEEPER_CLIENT_PORT,
                props.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENT_PORT));
        conf.set("hbase.zookeeper.quorum", props
                .getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_QUORUM));
        conf.set(
                "hbase.zookeeper.property.clientPort",
                props.getProperty(Constants.HBASE_CONFIGURATION_ZOOKEEPER_CLIENT_PORT));
    }

    public List<String> getAllKeyword(String tableName, String rowKey)
            throws IOException {
        List<String> qualifiers = new ArrayList<String>();
        HTable table = new HTable(conf, tableName);
        Get get = new Get(rowKey.getBytes());
        Result rs = table.get(get);

        for (KeyValue kv : rs.raw()) {

            System.out.println("KV: " + kv + ", keyword: "
                    + Bytes.toString(kv.getRow()) + ", quaifier: "
                    + Bytes.toString(kv.getQualifier()) + ", family: "
                    + Bytes.toString(kv.getFamily()) + ", value: "
                    + Bytes.toString(kv.getValue()));
            qualifiers.add(new String(kv.getQualifier()));
        }
        table.close();
        return qualifiers;

    }
    /**
     * Create a table
     * 
     * @param tableName
     *            name of table to be created.
     * @param familys
     *            Array of the name of column families to be created with table
     * @throws IOException
     */
    public boolean creatTable(String tableName, String[] familys) {
        HBaseAdmin admin = null;
        boolean tableCreated = false;
        try {
            admin = new HBaseAdmin(conf);
            if (!admin.tableExists(tableName)) {
                HTableDescriptor tableDesc = new HTableDescriptor(tableName);
                for (int i = 0; i < familys.length; i++) {
                    tableDesc.addFamily(new HColumnDescriptor(familys[i]));
                }
                admin.createTable(tableDesc);
                System.out.println("create table " + tableName + " ok.");
            }
            tableCreated = true;
            admin.close();
        } catch (MasterNotRunningException e1) {
            e1.printStackTrace();
        } catch (ZooKeeperConnectionException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return tableCreated;
    }

}

Below is my Test class.

@RunWith(PowerMockRunner.class)
@PrepareForTest(MessageProcessor1.class)
@SuppressStaticInitializationFor("com.serendio.msg.mqProcessor.MessageProcessor1")
public class MessageProcessorTest1 {

    private MessageProcessor1 messageProcessor;
    private HbaseUtil1 hbaseUtil;

    @Before
    public void setUp() {
        messageProcessor = new MessageProcessor1();
        hbaseUtil = EasyMock.createMock(HbaseUtil1.class);
    }


    @Test
    public void testListAllKeyword(){
        List<String> expectedList = new ArrayList<String>();
        expectedList.add("raj:abc");
        suppress(constructor(HbaseUtil1.class));
        //suppress(method(HbaseUtil1.class, "getAllKeyword"));

        try {
            EasyMock.expect(hbaseUtil.getAllKeyword("msg", "u1")).andReturn(expectedList);
            EasyMock.replay();
            assertEquals("raj", messageProcessor.listAllKeyword("u1"));
        } catch (IOException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

1 Answer 1

0

The HbaseUtil1 is instantiated within the listAllKeyword method

 public String listAllKeyword(String userId) throws IOException {
     HbaseUtil1 util = new HbaseUtil1();
     ...

So the mock one you create in your test isn't being used at all. If possible, make the HbaseUtil1 object passable, or settable on the MessageProcessor1 class and then set it in the test class.

Also, and note I'm not 100% familiar with PowerMock, you could include HbaseUtil1 in the prepare for test annotation. I think that will make PowerMock instantiate mocks instead of real objects and then use the expectations you provide in you test.

4
  • @user3327151 Is there any reason you need to instantiate a separate HbaseUtil1 for this method then? If the MessageProcessor1 already has one set, there should be no need to instantiate a new one and use that one instead. I would remove the HbaseUtil1 util = new HbaseUtil1(); from the listAllKeyword method and use the hbaseUtil from the MessageProcessor1, so you get List<String> qualifiers = hbaseUtil.getAllKeyword("msg", userId) Then in the test class, add messageProcessor.setHbaseUtil(hbaseUtil); as the last line in the setUp method.
    – Dan Temple
    Feb 19, 2014 at 10:31
  • I passed HbaseUtil1 as setter and it worked fine. its not calling actual method now but its giving null point exception for qualifiers. //HbaseUtil1 util = new HbaseUtil1(); Map<String, List<String>> projKeyMap = new HashMap<String, List<String>>(); List<String> qualifiers = hbaseUtil.getAllKeyword("msg", userId); List<String> keywords = null; for (String qualifier : qualifiers) { String[] token = qualifier.split(":"); Feb 19, 2014 at 10:31
  • thanks for ur help bro.. but still test is not passed bcoz of null value returned to qualifiers. could u pls find whr am goin wrong ? Feb 19, 2014 at 17:42
  • Here are the MessageProcessor1 and the test class in ideone: ideone.com/otEWQi These classes have the changes I've suggested. Can you confirm that they're definitely like this. If so, it should be working....
    – Dan Temple
    Feb 20, 2014 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.