共计 1245 个字符,预计需要花费 4 分钟才能阅读完成。
- 如果测试类是 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;}
}
- 如何定义测试类
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"));
}
}
正文完