gpt4 book ai didi

java - assertEqual NullPointerException 的 JUnit 测试

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:28 26 4
gpt4 key购买 nike

我不确定为什么测试用例没有输出 true。这两种情况都应该给出一个 NullPointerException

我试过这样做(不完全相同,但它给出了 true 的输出):

    String nullStr = null;

//@Test
public int NullOutput1() {
nullStr.indexOf(3);
return 0;
}

//@Test(expected=NullPointerException.class)
public int NullOutput2() {
nullStr.indexOf(2);
return 0;
}

@Test(expected=NullPointerException.class)
public void testboth() {
assertEquals(NullOutput1(), NullOutput2());
}

运行者:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunnerStringMethods {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(TestJunitMyIndexOf.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}

方法:

public static int myIndexOf(char[] str, int ch, int index) {
if (str == null) {
throw new NullPointerException();
}
// increase efficiency
if (str.length <= index || index < 0) {
return -1;
}
for (int i = index; i < str.length; i++) {
if (index == str[i]) {
return i;
}
}
// if not found
return -1;
}

测试用例:

@Test(expected=NullPointerException.class)
public void testNullInput() {
assertEquals(nullString.indexOf(3), StringMethods.myIndexOf(null, 'd',3));
}

最佳答案

我相信你想在这里使用fail:

@Test(expected=NullPointerException.class)
public void testNullInput() {
fail(nullString.indexOf(3));
}

如果需要,请确保添加 import static org.junit.Assert.fail;

关于java - assertEqual NullPointerException 的 JUnit 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22623649/

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