简体   繁体   中英

Mocking external service returns null

I got pretty simple Dictionary class that makes a call to external 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() .

    @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

return output.getValue();

Can someone point me what I did wrong?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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