简体   繁体   English

模拟外部服务返回null

[英]Mocking external service returns null

I got pretty simple Dictionary class that makes a call to external API. 我有一个非常简单的Dictionary类,可以调用外部API。

 public class Dictionary {
        protected ExternalService service = new ExternalService();       

        public String getValue(String key, String dictionaryName) {
            ExternalServiceInput input = new ExternalServiceInput();
            ExternalServiceOutput output = new ExternalServiceOutput();

            input.setKey(key);
            input.setDictionaryName(dictionaryName);

            try {
                output = service.invoke(input);
            } catch (Exception e) {         
                return null;
            }       

            return output.getValue();       
        }
    }

It works fine, but I wanted to write Unit Tests for this, so I decided I need to mock service.invoke() . 它工作正常,但是我想为此编写单元测试,所以我决定需要模拟service.invoke()

    @Mock   
    private ExternalService service;        

    @InjectMocks
    private Dictionary dictionary;      
    @InjectMocks
    private ExternalServiceOutput output;
    @InjectMocks
    private ExternalServiceInput input;


    @Before
    public void setUp() throws Exception {      
        MockitoAnnotations.initMocks(this);

        input.setKey("testKey");
        input.setDictionaryName("testDictionary");  
        output.setValue("testValue");           
    }

    @Test
    public void shouldReturnValue() throws Exception {
        when(service.invoke(input)).thenReturn(output);     
        assertEquals(output.getValue(), dictionary.getValue(input.getKey(), input.getDictionaryName()));        
    }

I'v tried with Input and Output as regular field or initialize it in setUp method, everything ends up with NullPointerException at Dictionary class at 我尝试将InputOutput用作常规字段,或者在setUp方法中对其进行了初始化,一切都以Dictionary类的NullPointerException结尾于

return output.getValue();

Can someone point me what I did wrong? 有人可以指出我做错了什么吗?

您应该在ExternalServiceInput类中重写equals和hashCode,或者更改您的模拟以接受ExternalServiceInput的任何对象

when(service.invoke(Mockito.any(ExternalServiceInput.class))).thenReturn(output);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM