模拟递归 class

mocking a recursive class

使用 Spring 2.0.3.RELEASE、JUnit Jupiter 5.7.0、Mockito 3.3.3

尝试测试 class 类 01 的方法 method01:

public class Class01 {

 private RestConnector con;
 
 public Class01(){
  con = RestConnector.getInstance();
 }

 public Response method01(String x) {
  Class01 example = new Class01();
  String x = example.isAuthenticated();
  
  // more stuff after this
  
 }
 
 public String isAuthenticated() throws IOException {
  // I do stuff
  return "a string";
 }

}  

正在测试class已尝试

public class Class01Test{

 @Mock private Class01 class01Mock;
 
 @Spy @InjectMocks private Class01 class01;

 @Test
 public void test() throws Throwable {
  
  doReturn("I returned").when(class01).  ??? stuck here .. always goes into the isAuthenticated method
  Response result = class01.method01("a string");
 }

}

目前测试始终是 运行 真正的方法 isAuthenticated。 如何为方法 method01 中的字段示例设置模拟,以便执行跳过进入方法 isAuthenticated?

try to test method method01 of class Class01

那你就不需要模拟了。

 @Test
 public void test() throws Throwable {
  Class01 c = new Class01();

  Response expected = ... ;
  assertEquals(c.method01("input"), expected);
 }

如果你想将行为注入example变量,你需要将它移动到一个字段

public class Class01 {

 private RestConnector con;
 private Class01 inner;
 
 public Class01(){
  con = RestConnector.getInstance();
 }

 Class01(Class01 c) {
   this();
   this.inner = c;
 }

 public Response method01(String x) {
  String x = inner.isAuthenticated();
  
  // more stuff after this
  
 }

连同 Mock

@RunWith(MockitoJunitRunner.class)
public class Class01Test{

 @Mock Class01 class01Mock;

 @Test
 public void test() throws Throwable {
  Response expected = ... ;
  when(class01Mock.isAuthenticated()).thenReture(expected); ... // TODO: Setup  
 
  Class01 c = new Class01(class01Mock); // pass in the mock
  
  assertEquals(c.method01("input"), expected);
 }

但是,不清楚为什么你需要一个相同 class 的嵌套对象,而你似乎只需要 this.isAuthenticated()

理想情况下,您还可以模拟 RestConnector