import javax.swing.*; import java.io.*; import java.awt.*; public class StudentPicture extends JPanel{ File imageFile; Toolkit tool; public StudentPicture(){ tool=getToolkit(); } public void setImage(File imageFile){ this.imageFile=imageFile; repaint(); } public void paintComponent(Graphics g){ super.paintComponent(g); int w=getBounds().width; int h=getBounds().height; if(imageFile!=null){ Image image=tool.getImage(imageFile.getAbsolutePath()); g.drawImage(image,0,0,w,h,this); } else g.drawString("没有选择照片图像",20,30); } } 编写该代码的junit类代码
时间: 2024-03-31 14:34:52 浏览: 164
view_image.rar_images view java_jpg view_view ima_view_image
以下是可能的JUnit测试类代码:
import static org.junit.Assert.*;
import org.junit.Test;
import java.io.*;
public class StudentPictureTest {
@Test
public void testSetImage() {
StudentPicture picture = new StudentPicture();
// test with null file
picture.setImage(null);
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
picture.paintComponent(null);
assertEquals("没有选择照片图像", outContent.toString().trim());
// test with existing file
File file = new File("test.png");
picture.setImage(file);
outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
picture.paintComponent(null);
assertNotNull(outContent.toString()); // image should be drawn
file.delete(); // clean up
}
}
注:此测试类假定在当前目录中存在名为“test.png”的测试图像文件。
阅读全文