mockito 总结

  1. 如果测试类是A,被测试方法是funcA
@Component
public class A {

    @Autowired
    private B b;

    public String funcA(String name) {
        return b.getName(name, false);
    }
}
@Component
public class B {

    public String getName(String name, boolean flag) {
        return name + ":" + flag;
    }
}
  1. 如何定义测试类
import static org.junit.jupiter.api.Assertions.*;

import org.junit.Before;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.*;

@ExtendWith(MockitoExtension.class)
class ATest {
    @InjectMocks
    private A a;

    @Mock
    private B b;
    
    @Before
    public void setUp(){
        // 通过反射给属性,常量或者静态变量赋值
    }

    @Test
    public void test() {
        String name = a.funcA("name");

        assertEquals(name, "name:");

        verify(b).getName(anyString(), false);

        doCallRealMethod().when(a).funcA(anyString());

        given(b.getName(anyString(), eq(false))).willReturn("zhangsan");
        assertEquals("zhangsan", "name:");

        doThrow(new RuntimeException("error msg")).when(b).getName(anyString(), eq(false));
        RuntimeException runtimeException = assertThrows(RuntimeException.class, () -> a.funcA("name"));
    }
}

你可能感兴趣的:(mockito)