Using Mockito, how do I match against the key-value pair of a map?

后端 未结 4 1156
清酒与你
清酒与你 2021-02-12 11:50

I need to send a specific value from a mock object based on a specific key value.

From the concrete class:

map.put(\"xpath\", \"PRICE\");
search(map);
         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-12 12:14

    Seems like what you need is an Answer:

    IOurXMLDocument doc = mock(IOurXMLDocument.class);
    when(doc.search(Matchers.>any())).thenAnswer(new Answer() {
        @Override
        public String answer(InvocationOnMock invocation) throws Throwable {
            Map map = (Map) invocation.getArguments()[0];
            String value = map.get("xpath");
            if ("PRICE".equals(value)) {
                return "$100.00";
            } else if ("PRODUCTNAME".equals(value)) {
                return "Candybar";
            } else {
                return null;
            }
        }
    });
    

    But what seems like a better idea is to not use primitive Map as parameter to your search method - you could probably transform this map into a pojo with price and productName attributes. Just an idea :)

提交回复
热议问题