gpt4 book ai didi

java - mockito 中的部分模拟 - 强制方法进入异常并继续

转载 作者:行者123 更新时间:2023-12-02 08:06:31 25 4
gpt4 key购买 nike

我有一个带有一些逻辑和异常 block 的方法,并且想测试异常 block 中的内容。

方法:

Class Validator() {

protected Validator(blah,blah) {

}

protected boolean doStuff(String a, String b) {

try {
isValidInput(a){
} catch (Exception e) {
b = "unknown error"
}
}

测试用例:

@Test
public void testException() {

Validator testValidator = new testValidator(blah, blah);

Validator spy = spy(testValidator);
String var2 = "unknown error"
doReturn(new Exception()).when(spy.doStuff(var1, var2));

assertEquals("unknown error", var2);
}

如何强制真正的方法进入异常 block 并继续 stub ?

最佳答案

首先,忘记使用spy - 如果isValidInput能够抛出异常,那么让它抛出异常

如果在 isValidInput() 中使用的协作者可以抛出 Exception,则使用 Mockito 模拟。如果这只是您的代码,那么您应该能够设置 a 以便生成异常。

您仍然需要在 isValidInput() 上编写一整套测试 - 使用 @Test 注释中的 expected 选项进行调查(我假设您正在使用 JUnit此处)指定抛出异常是测试的预期结果。但请不要抛出 Exception - 使用它的有意义的子类:-)

正如 @Dave Newton 评论的那样,测试 var2 永远不会在 doStuff 的范围之外工作。

关于java - mockito 中的部分模拟 - 强制方法进入异常并继续,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8087516/

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