【问题标题】:mocking a recursive class模拟递归类
【发布时间】:2021-07-16 20:39:56
【问题描述】:

使用 Spring 2.0.3.RELEASE、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");
 }

}

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

【问题讨论】:

  • 自从method01 创建了一个新实例后,mock 从未被使用过。但是为什么会在method01 中创建一个新实例?如果确实需要,则通过构造函数注入模拟或作为参数传递。
  • 据我所知,这是在尝试连接到外部服务器。如果失败,它会尝试另一个位置。不遵循“通过构造函数注入模拟或作为参数传递”的意思

标签: java junit mockito junit5


【解决方案1】:

尝试测试类Class01的方法method01

那么你就不需要模拟了。

 @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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-07
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多