gpt4 book ai didi

java - 模拟回调

转载 作者:行者123 更新时间:2023-12-04 03:40:21 25 4
gpt4 key购买 nike

我正在尝试测试使用回调的第 3 方库。

Db db;
db.find("param", new DbCallback() {
public void onComplete(Result r) {
//my business logic with r
r.get("name"); //etc
}
});

这是我的测试对象 Foo 类内部。它看起来像这样:

class Foo {

@Autowired
Db db;

void bar() {
db.find("param", new DbCallback() {
public void onComplete(Result r) {
// my business logic with r
r.get("name"); //etc
}
});
}
}

到目前为止我的测试是这样的:

class FooTest {
@InjectMocks
Foo foo; // test subject

@Mock
Db db; //thing I want to mock

// initMocks etc.

@Test
void bar() {
when(db.find( ??? )).then???
foo.bar();
// asserts etc.
}
}

但我不完全确定如何在此处使用when

如果这是一种“常规”方法,我会使用

when(db.find(anyString()).thenReturn(fakeData)

最佳答案

只要您使用 Spring 组件,我强烈建议您通过 Spring 包 org.springframework.boot.test.mock.mockito 使用 Mockito 使用特定的 Spring 测试注释来限制自己模拟或监视 bean .在 @MockBean 的 JavaDoc 上可以看到一个很好的例子.翻译成您的代码示例:

@MockBean    // this annotation creates a mock bean in Spring context
Db db; // thing I want to mock

@Autowired // injected as usual with the preference of mocked beans dependencies
Foo foo; // test subject

当然,对于所使用的每个 jUnit 版本,测试类注释都不同:

  • jUnit 4:@RunWith(SpringJUnit4ClassRunner.class)
  • jUnit 5:@ExtendWith(SpringExtension.class)

回到您的问题,when-then 构造变得相当简单。使用 Mockito 类的静态方法,您可以定义哪些对象类型应该作为方法参数出现(类型的“任何”值或特定值)。

它还取决于方法 Db#findvoid 还是具有返回类型。

  • 该方法有一个返回类型:
    // the data object doesn't need to be a mock
    DbFindMethodReturnType mockData = new DbFindMethodReturnType(...);

    Mockito.when(db.find(
    Mockito.eq("params"), // Mockito.anyString() for any string
    Mockito.any(DbCallback.class))) // Mockito.any() is also possible
    .thenReturn(mockData)
  • 方法是void:
    Mockito.doNothing()
    .when(db)
    .find(Mockito.eq("params"), Mockito.any(DbCallback.class));

关于java - 模拟回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66162542/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com