方法调用在单元测试时没有发生



我有下面的代码试图进行单元测试

@Service
class MainClass {
public void simpleExe() {
webclient.post()
.uri("url")
.header(----)
.bodyValue(ReqPojo)
.retrieve()
.bodyToMono(Response.class)
.flatMap(this::add); **this line is running but the call not happening to add method**
}
private Mono<Response> add() {
// doing some calculation
}
}

测试类

@SpringBootTest
class MainClassTest {
//mocked few other service calls
@Autowired
MainClass mainClass;
@Test
public void testsimpleExe() {
mainClass.simpleExe();
}
}

this::add控件进入本行,但没有调用add方法。有什么问题吗?少了什么东西吗?

从第一个代码片段来看,int a = this::add;行不能编译,因为类型不兼容:

@Service
public class MainClass {
public void simpleExe() {
int a = this::add; // DOES NOT COMPILE
}
private int add() {
return 42;
}
}

如果你想使用接受零参数并返回int的方法引用,你可以使用IntSupplier函数接口:

import org.springframework.stereotype.Service;
import java.util.function.IntSupplier;
@Service
public class MainClass {
IntSupplier add = () -> {
// some calculations
return 42;
};
public void simpleExe() {
int a = add.getAsInt();
System.out.println("a = " + a);
// ...
}
}

最新更新