1、异常详细描述
Test ignored.
org.junit.platform.commons.PreconditionViolationException: Class [org.bc.offer.datastructure.Stack] must declare a single constructor
Process finished with exit code -1
2、源码
package org.bc.offer.datastructure;
import org.junit.jupiter.api.Test;
/**
*
* @description:
* @author:bc
* @date: 2023/06/29
*
* 基于数组实现的顺序栈
*
**/
public class Stack<E> {
private Object [] data=null;
private int maxSize=0;//栈的大小
private int top=-1;//栈顶的指针
public Stack(){
this(10);
}
public Stack(int initialSize){
if(initialSize>=0){
this.maxSize=initialSize;
data=new Object[initialSize];
top=-1;
}else{
throw new RuntimeException("初始化大小不能小于0:"+initialSize);
}
}
public boolean push(E e){
if(top==maxSize-1){
throw new RuntimeException("栈已满,无法将元素入栈");
}else{
data[++top]=e;
}
return true;
}
public E pop(){
if(top==-1){
throw new RuntimeException("栈为空");
}else{
return (E) data[top--];
}
}
public E peek(){
if(top==-1){
throw new RuntimeException("栈为空");
}else{
return (E) data[top];
}
}
@Test
public void testStack(){
Stack stack=new Stack(10);
stack.push(2);
stack.push(1);
stack.push(5);
stack.push(6);
for(int i=0;i<10;i++) {
System.out.println(stack.pop() + "");
}
}
}
3、修改后源码:
package org.bc.offer.datastructure;
import org.junit.jupiter.api.Test;
/**
*
* @description:
* @author:bc
* @date: 2023/06/29
*
* 基于数组实现的顺序栈
*
**/
public class Stack<E> {
private Object [] data=null;
private int maxSize=0;//栈的大小
private int top=-1;//栈顶的指针
public Stack(){
int initialSize=10;
if(initialSize>=0){
this.maxSize=initialSize;
data=new Object[initialSize];
top=-1;
}else{
throw new RuntimeException("初始化大小不能小于0:"+initialSize);
}
}
public boolean push(E e){
if(top==maxSize-1){
throw new RuntimeException("栈已满,无法将元素入栈");
}else{
data[++top]=e;
}
return true;
}
public E pop(){
if(top==-1){
throw new RuntimeException("栈为空");
}else{
return (E) data[top--];
}
}
public E peek(){
if(top==-1){
throw new RuntimeException("栈为空");
}else{
return (E) data[top];
}
}
@Test
public void testStack(){
Stack stack=new Stack();
stack.push(2);
stack.push(1);
stack.push(5);
stack.push(6);
for(int i=0;i<10;i++) {
System.out.println(stack.pop() + "");
}
}
}
4、解释
org.junit.jupiter.api.Test
这个单元测试框架,不允许@Test 标注的方法所在的类存在有参构造器,一旦存在,便报一下异常另外,该测试框架也不允许有多个构造器,如果存在多个构造器,则报一下错误
must declare a single constructor