【发布时间】:2019-03-21 04:04:50
【问题描述】:
这里有两个 Spring Service;
public interface Service01 {
String test01(String name);
}
@Service
public class Service01Impl implements Service01 {
@Override
public String test01(String name) {
if (!"123".equals(name)) {
throw new RuntimeException("name is illegal");
}
return name;
}
}
@Service
public class Service02 {
@Autowired
private Service01 service01;
@Autowired
private Service03 service03;
public String test02(String name) {
service03.checkNameNotNull(name);
return service01.test01(name);
}
}
@Service
public class Service03 {
public void checkNameNotNull(String name) {
if (name == null) {
throw new RuntimeException("name is null");
}
}
}
那么这是我的测试类:
public class TestCalss {
@Mock
private Service01 service01;
@Autowired
private Service02 service02;
@Test
public void testMock() {
// mock service
when(service01.name("abc")).thenReturn("mock return abc");
// here will be success
String nameAbc = service01.test01("abc")
Assert.assertEquals("mock return abc", nameAbc);
// but here got exception: `name is illegal`
String name = service02.test02("abc");
Assert.assertEquals("mock return abc", name);
}
}
第一季度:
为什么在行出现异常:String name = service02.test02("abc");
java.lang.RuntimeException: name is illegal
Q2:当我调用Service02 时如何模拟Service01?
--编辑
Q2 用@InjectMocks 修复
第三季度:
如何只模拟Service01,但不模拟Service03。
我想让这张支票没有模拟
service03.checkNameNotNull(name);
【问题讨论】:
标签: spring spring-boot mockito junit4