๐Ÿงช Week 23, Day 1: System Testing & Debugging

๐ŸŽฏ Learning Objectives

๐Ÿ” Types of Testing

Testing Pyramid

Type Description Example
Unit Testing Test individual functions/methods Test that isAvailable() returns correct value
Feature Testing Test complete features/endpoints Test that book creation works end-to-end
Integration Testing Test multiple components working together Test borrowing system with database and emails
Manual Testing Human testing of user interface Click through application as a real user

โœ… Manual Testing Checklist

Complete Test Cases

1. Authentication Module

Test Case Steps Expected Result Status
User Registration 1. Go to /register
2. Fill form with valid data
3. Submit
User created, redirected to dashboard โ˜
Registration Validation 1. Submit empty form
2. Check error messages
Validation errors shown โ˜
User Login 1. Go to /login
2. Enter credentials
3. Submit
User logged in, dashboard shown โ˜
Invalid Login 1. Enter wrong password
2. Submit
Error message displayed โ˜
Logout 1. Click logout button User logged out, redirected to home โ˜

2. Book Management Module

Test Case Steps Expected Result Status
View All Books 1. Navigate to /books Books displayed in grid layout โ˜
Add New Book 1. Click "Add Book"
2. Fill form
3. Upload image
4. Submit
Book created, appears in list โ˜
Edit Book 1. Click "Edit" on book
2. Modify data
3. Submit
Book updated, changes reflected โ˜
Delete Book 1. Click "Delete"
2. Confirm
Book removed from database โ˜
Search Books 1. Enter search term
2. Submit
Filtered results displayed โ˜
Filter by Category 1. Select category
2. Submit
Books from that category shown โ˜

3. Borrowing System Module

Test Case Steps Expected Result Status
Borrow Book 1. Select book
2. Select user
3. Submit
Borrowing created, book availability decremented, email sent โ˜
Return Book 1. Click "Return"
2. Confirm
Book marked returned, availability incremented โ˜
Overdue Book 1. Return book after due date Fine calculated and created โ˜
Cannot Borrow Unavailable 1. Try to borrow book with 0 quantity Error message shown โ˜

๐Ÿ”ฌ Automated Testing with PHPUnit

Writing Feature Tests

Create Test File

php artisan make:test BookTest

Example Test Cases

// tests/Feature/BookTest.php
namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use App\Models\Book;
use App\Models\Category;
use Illuminate\Foundation\Testing\RefreshDatabase;

class BookTest extends TestCase
{
    use RefreshDatabase;

    /** @test */
    public function authenticated_users_can_view_books()
    {
        $user = User::factory()->create();
        
        $response = $this->actingAs($user)->get('/books');
        
        $response->assertStatus(200);
        $response->assertViewIs('books.index');
    }

    /** @test */
    public function users_can_create_a_book()
    {
        $user = User::factory()->create(['is_admin' => true]);
        $category = Category::factory()->create();
        
        $bookData = [
            'title' => 'Test Book',
            'author' => 'Test Author',
            'isbn' => '1234567890',
            'category_id' => $category->id,
            'quantity' => 5,
            'description' => 'Test description'
        ];
        
        $response = $this->actingAs($user)
                         ->post('/books', $bookData);
        
        $this->assertDatabaseHas('books', [
            'title' => 'Test Book',
            'author' => 'Test Author'
        ]);
        
        $response->assertRedirect('/books');
    }

    /** @test */
    public function book_title_is_required()
    {
        $user = User::factory()->create(['is_admin' => true]);
        $category = Category::factory()->create();
        
        $response = $this->actingAs($user)
                         ->post('/books', [
                             'title' => '',
                             'author' => 'Test Author',
                             'isbn' => '1234567890',
                             'category_id' => $category->id,
                             'quantity' => 5
                         ]);
        
        $response->assertSessionHasErrors('title');
    }

    /** @test */
    public function users_can_search_books()
    {
        $user = User::factory()->create();
        $category = Category::factory()->create();
        
        Book::factory()->create([
            'title' => 'Laravel Tutorial',
            'category_id' => $category->id
        ]);
        
        Book::factory()->create([
            'title' => 'PHP Basics',
            'category_id' => $category->id
        ]);
        
        $response = $this->actingAs($user)
                         ->get('/books?search=Laravel');
        
        $response->assertSee('Laravel Tutorial');
        $response->assertDontSee('PHP Basics');
    }

    /** @test */
    public function book_availability_decreases_when_borrowed()
    {
        $user = User::factory()->create();
        $category = Category::factory()->create();
        $book = Book::factory()->create([
            'category_id' => $category->id,
            'quantity' => 5,
            'available_quantity' => 5
        ]);
        
        $this->actingAs($user)
             ->post('/borrowings', [
                 'book_id' => $book->id,
                 'user_id' => $user->id
             ]);
        
        $book->refresh();
        $this->assertEquals(4, $book->available_quantity);
    }
}

# Run tests
php artisan test

๐Ÿ› Debugging Techniques

Laravel Debugging Tools

1. dd() - Dump and Die

// Dump variable and stop execution
dd($books);

// Dump multiple variables
dd($books, $categories, $user);

2. dump() - Dump Without Stopping

// Dump and continue execution
dump($book);
dump($user);
return view('books.show', compact('book'));

3. Laravel Debugbar

# Install Laravel Debugbar
composer require barryvdh/laravel-debugbar --dev

# It will show:
# - SQL queries executed
# - Execution time
# - Memory usage
# - Request data
# - Session data

4. Log Files

// Write to log file
\Log::info('Book created', ['book_id' => $book->id]);
\Log::error('Error borrowing book', ['error' => $e->getMessage()]);
\Log::debug('Debug info', ['data' => $data]);

# View logs
tail -f storage/logs/laravel.log

5. Tinker - Interactive Shell

php artisan tinker

# Test queries
>>> App\Models\Book::count()
>>> App\Models\User::where('email', 'test@example.com')->first()
>>> $book = App\Models\Book::find(1)
>>> $book->borrowings

๐Ÿ”ง Common Bugs and Solutions

Bug Fix Examples

Bug 1: N+1 Query Problem

// Problem: This generates 101 queries (1 + 100)
$borrowings = Borrowing::all(); // 1 query
foreach ($borrowings as $borrowing) {
    echo $borrowing->book->title; // 100 queries
}

// Solution: Use eager loading
$borrowings = Borrowing::with(['book', 'user'])->get(); // 3 queries total

Bug 2: Mass Assignment Error

// Problem: "Add [field] to fillable property"
Book::create($request->all()); // Error!

// Solution: Add to $fillable array in model
protected $fillable = [
    'title', 'author', 'isbn', 'category_id', 
    'description', 'quantity', 'available_quantity'
];

Bug 3: File Upload Not Working

// Problem: Images not displaying

// Solution 1: Create symbolic link
php artisan storage:link

// Solution 2: Update form to include enctype
<form method="POST" enctype="multipart/form-data">

// Solution 3: Check file validation
$request->validate([
    'cover_image' => 'nullable|image|mimes:jpeg,png,jpg|max:2048'
]);

โœ๏ธ Today's Tasks

Task 1: Manual Testing (2 hours)

  1. Test all authentication flows
  2. Test all CRUD operations for books
  3. Test borrowing and return flows
  4. Test search and filter functionality
  5. Test on different browsers (Chrome, Firefox, Edge)
  6. Test on mobile devices
  7. Document all bugs found

Task 2: Write Automated Tests (60 minutes)

  1. Create BookTest with 5 test cases
  2. Create BorrowingTest with 3 test cases
  3. Run tests and ensure they pass
  4. Fix any failing tests

Task 3: Bug Fixing (90 minutes)

  1. Prioritize bugs (critical, high, medium, low)
  2. Fix all critical bugs first
  3. Fix high priority bugs
  4. Retest after each fix
  5. Update bug tracking document

Task 4: Performance Testing (30 minutes)

  1. Check page load times
  2. Optimize slow queries
  3. Add database indexes if needed
  4. Test with large datasets

๐Ÿ“ฆ Deliverables

By end of day:

  1. Tested Application:
    • All test cases executed
    • Test results documented
  2. Automated Tests:
    • Minimum 8 passing tests
    • Tests cover critical features
  3. Bug Report:
    • List of bugs found
    • Priority levels assigned
    • Status (fixed/pending)
  4. Stable Application:
    • All critical bugs fixed
    • No broken features
    • Ready for deployment
๐Ÿ’ก Testing Best Practices: