有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java模拟递归类

使用Spring 2.0.3。发布版,JUnit Jupiter 5.7.0,Mockito 3.3.3

尝试测试Class01的方法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";
 }

}  

在测试课上,我试过

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");
 }

}

目前测试总是在运行,真正的方法是经过验证的。 如何为method01中的字段示例设置一个模拟,以使进入方法的执行跳过得到验证


共 (1) 个答案

  1. # 1 楼答案

    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
      
     }
    

    还有一个模拟的

    @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);
     }
    
    

    然而,,不清楚当你看起来只需要this.isAuthenticated()时,为什么你需要同一类的嵌套对象

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