模拟外部服务 returns 空

Mocking external service returns null

我很简单 Dictionary class 调用外部 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();       
        }
    }

它工作正常,但我想为此编写单元测试,所以我决定我需要模拟 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()));        
    }

我已经尝试将 InputOutput 作为常规字段或在 setUp 方法中对其进行初始化,一切都以 NullPointerException at Dictionary 结束class 在

return output.getValue();

谁能指出我做错了什么?

您应该覆盖 ExternalServiceInput 中的 equals 和 hashCode class 或更改您的模拟以接受 ExternalServiceInput

的任何对象
when(service.invoke(Mockito.any(ExternalServiceInput.class))).thenReturn(output);