Injection of a mock object into an object to be tested declared as a field in the test does not work using Mockito?

前端 未结 2 1901
春和景丽
春和景丽 2021-01-01 02:30

I have a class and I am injecting a proxy into my service.

Service service
{
    private ServiceProxy proxy;
    public Service(ServiceProxy proxy)
    {
           


        
2条回答
  •  星月不相逢
    2021-01-01 02:49

    Write your test class as this, which will initialize Service with a mock of ServiceProxy:

    class ServiceTest
    {
    @Mock
    ServiceProxy mockProxy;
    
    //This will inject the "ServiceProxy" mock into your "Service" instance.
    @InjectMocks
    Service service = new Service(mockProxy);
    
    @Before
    public void init() {
    //This will initialize the annotated mocks 
    MockitoAnnotations.initMocks(this);
    }
    
    @Test
    public void test() {
    ... 
    }
    }
    

提交回复
热议问题