跳至主要內容

InjectMocks


InjectMocks

@InjectMocks注解会自动注入相应对象所需要的变量。

import java.util.Random;

public class HttpService {

    public int queryStatus() {
        // 发起网络请求,提取返回结果
        // 这里用随机数模拟结果
        return new Random().nextInt(2);
    }

}
public class UseHttpService {

    private HttpService httpService;

    public String hello() {
        int status = httpService.queryStatus();
        if(status == 0){
            return "你好";
        }else if(status == 1){
            return "Hello";
        }else{
            return "未知状态";
        }
    }

}
import org.junit.Assert;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.when;

public class InjectMocksTest {

    @Mock
    private HttpService httpService;

    //如果使用@Mock则会产生空指针异常
    @InjectMocks
    private UseHttpService useHttpService;

    @Test
    public void injectMocksTest(){
        MockitoAnnotations.initMocks(this);
        when(httpService.queryStatus()).thenReturn(0);
        Assert.assertEquals("你好",useHttpService.hello());
    }
}
上次编辑于:
贡献者: Neil