public void addBook(Book b){ String sql="insert into Book values('"+b.getBook_ISBN()+"','"+b.getBook_category()+"','"+b.getBook_name()+"','"+b.getBook_author()+"','"+b.getPublish_house()+"','"+b.getPublish_time()+"','"+b.getBook_price()+"','"+b.getBook_sum()+"','"+b.getBook_remain()+"','"+b.getBook_introduce()+"')"; Object params[]={b.getBook_ISBN(),b.getBook_category(),b.getBook_name(),b.getBook_author(),b.getPublish_house(),b.getPublish_time(),b.getBook_price(),b.getBook_sum(),b.getBook_sum(),b.getBook_remain(),b.getBook_introduce()}; DBHelper.executeUpdate(sql,params); }实现junit测试的代码
时间: 2024-03-23 10:39:21 浏览: 116
Spring+SpringMVC+Mybatis SSM框架整合
可以参考以下代码实现JUnit测试:
```java
import static org.junit.Assert.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.junit.Test;
public class BookTest {
@Test
public void testAddBook() {
// 创建一个模拟的DBHelper对象
DBHelper mockDBHelper = mock(DBHelper.class);
// 创建一个Book对象
Book book = new Book();
book.setBook_ISBN("1234567890");
book.setBook_category("Programming");
book.setBook_name("Java Programming");
book.setBook_author("John Smith");
book.setPublish_house("Publishing House");
book.setPublish_time("2022-01-01");
book.setBook_price(50.0);
book.setBook_sum(100);
book.setBook_remain(90);
book.setBook_introduce("Introduction");
// 创建一个BookDao对象
BookDao bookDao = new BookDao(mockDBHelper);
// 调用addBook方法
bookDao.addBook(book);
// 验证是否调用了DBHelper的executeUpdate方法,并传入了正确的参数
verify(mockDBHelper).executeUpdate("insert into Book values(?,?,?,?,?,?,?,?,?,?)",
book.getBook_ISBN(), book.getBook_category(), book.getBook_name(), book.getBook_author(),
book.getPublish_house(), book.getPublish_time(), book.getBook_price(), book.getBook_sum(),
book.getBook_remain(), book.getBook_introduce());
// 使用when和thenReturn方法模拟executeUpdate返回值
when(mockDBHelper.executeUpdate(any(String.class), any(Object[].class))).thenReturn(1);
// 调用addBook方法后,期望返回值为1
int result = bookDao.addBook(book);
assertEquals(1, result);
}
}
```
阅读全文