用java编写一个Book 类,用于描述个人藏书,包含作者Author、书名 Title、价格Price、出版社Publisher、出版年份 Published Year 共5个属性。然后编写一个测试类 BookTest,对Book类进行测试,输出正确的属性值。
时间: 2024-12-02 08:28:25 浏览: 138
在Java中,你可以按照以下步骤创建一个`Book`类以及一个测试类`BookTest`:
首先,我们定义一个名为`Book`的类,它有五个私有属性和对应的getter/setter方法:
```java
public class Book {
private Author author;
private String title;
private double price;
private String publisher;
private int publishedYear;
// 构造函数
public Book(Author author, String title, double price, String publisher, int publishedYear) {
this.author = author;
this.title = title;
this.price = price;
this.publisher = publisher;
this.publishedYear = publishedYear;
}
// getters and setters
public Author getAuthor() { return author; }
public void setAuthor(Author author) { this.author = author; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public double getPrice() { return price; }
public void setPrice(double price) { this.price = price; }
public String getPublisher() { return publisher; }
public void setPublisher(String publisher) { this.publisher = publisher; }
public int getPublishedYear() { return publishedYear; }
public void setPublishedYear(int publishedYear) { this.publishedYear = publishedYear; }
}
```
接下来,我们创建`Author`类,因为这里只关注`Book`类,所以我们可以简单地定义它:
```java
// 假设Author是一个简单的类,包含姓名
class Author {
private String name;
// ... (同样包含getter和setter)
}
```
现在,我们编写`BookTest`类来进行测试:
```java
import org.junit.Test;
public class BookTest {
@Test
public void testBookProperties() {
// 创建一个Book实例
Author author = new Author("John Doe");
Book book = new Book(author, "The Catcher in the Rye", 9.99, "Random House", 1951);
// 输出属性值
System.out.println("Author: " + book.getAuthor().getName());
System.out.println("Title: " + book.getTitle());
System.out.println("Price: $" + book.getPrice());
System.out.println("Publisher: " + book.getPublisher());
System.out.println("Published Year: " + book.getPublishedYear());
// 验证属性值是否正确
assert book.getAuthor().getName().equals("John Doe") : "Author name is incorrect";
assert book.getTitle().equals("The Catcher in the Rye") : "Title is incorrect";
assert book.getPrice() == 9.99 : "Price is incorrect";
assert book.getPublisher().equals("Random House") : "Publisher is incorrect";
assert book.getPublishedYear() == 1951 : "Published year is incorrect";
}
}
```
这个测试类会创建一个`Book`实例,并检查每个属性的值是否如预期。
阅读全文