UML Class Diagram Tests

1. Shared-Target Inheritance

Animal +name: str +speak() Dog +breed: str +fetch(item: str) Cat +indoor: bool +purr()

2. Interface Realization (Dashed Arrows)

«interface» Drawable +draw() Circle -radius: double +draw() Rectangle -width: double -height: double +draw()

3. All Relationship Types

«abstract» Shape -color: int +area(): double +setColor(r: int, g: int, b: int) Rectangle -width: int -length: int +setWidth(width: int) +setHeight(height: int) Color -r: int -g: int -b: int Canvas +render() Logger +log(msg: str) uses

4. Multiplicities and Labels

University +name: str Professor +name: str +department: str Student +name: str +id: int 1 * 1 * employs advises

4b. Navigability Combinations (Association / Aggregation / Composition)

AssocUnspecified AssocNavigable AssocBidirectional AssocNonNavigable AssocNonNavigableBoth AssocTarget AggUnspecified AggNavigable AggBidirectional AggNonNavigable AggTarget CompUnspecified CompNavigable CompBidirectional CompNonNavigable CompTarget association (unspecified) association (navigable) association (bidirectional) association (non-navigable) association (non-navigable both ends) aggregation (unspecified) aggregation (navigable) aggregation (bidirectional) aggregation (non-navigable) composition (unspecified) composition (navigable) composition (bidirectional) composition (non-navigable)

4c. Reverse-Direction Navigability (Explicit)

AssocL AssocR AssocL2 AssocR2 AggL AggR AggL2 AggR2 CompL CompR CompL2 CompR2 association (navigable to left) association (non-navigable to left) aggregation (navigable to left) aggregation (non-navigable to left) composition (navigable to left) composition (non-navigable to left)

4d. Tolerant Alias Forms

Alias1 Alias2 Alias3 alias for composition non-navigable alias for aggregation non-navigable

5. Observer Design Pattern

«interface» Observer +update(data: Object) «abstract» Subject -observers: List +attach(o: Observer) +detach(o: Observer) +notify() ConcreteSubject -state: int +getState(): int +setState(s: int) ConcreteObserverA +update(data: Object) ConcreteObserverB +update(data: Object) notifies

6. Train System (from Lecture)

Train -lastStop: char -nextStop: char -velocity: double -doorsOpen: boolean +startTrain(velocity: double): void +stopTrain(): void +openDoors(): void Station +name: str Button +pressed: boolean +press() RequestButton +press() EmergencyButton +press() 1 1 1 2

7. Dependency

Train +addStop(stop: event): void ButtonPressedEvent +station: str +timestamp: int

8. Abstract Class with Stereotype

«singleton» Singleton -instance: Singleton -data: str +getInstance(): Singleton +getData(): str

9. Note with Constraint (Bottom)

BankAccount +owner: String +balance: Number +deposit(amount: Number) +withdraw(amount: Number) {owner->notEmpty() and balance >= 0}

10. Multi-line Note with Code and LaTeX

Order +id: int +status: String +total: double Customer +name: String +email: String 1 * places Status transitions via updateStatus(): CREATED -> PAID -> SHIPPED Total must satisfy total >= 0

10b. Notes on Attributes and Operations

Account +owner: String +balance: double +deposit(amount: double) +withdraw(amount: double) Must not be null or empty Throws InsufficientFundsException

10b2. Observer Notes Avoid Relation Endpoints

«interface» Subject +attach(observer: Observer): void +detach(observer: Observer): void +notifyObservers(): void «interface» Observer +update(): void ConcreteSubject -subjectState: String +getState(): String +setState(value: String): void ConcreteObserver -subject: ConcreteSubject -observerState: String +update(): void 1 0..* observers subject for each o in observers { o.update() } getState() returns subjectState observerState = subject.getState()

10c. Note with Python Syntax Highlighting

BankAccount +owner: String +balance: float +deposit(amount: float) +withdraw(amount: float) def withdraw(self, amount): if amount <= 0: raise ValueError("Amount must be positive") if amount > self.balance: raise InsufficientFunds(self.balance) self.balance -= amount return self.balance

10d. Note with Java Syntax Highlighting

OrderService +placeOrder(order: Order): boolean public boolean placeOrder(Order order) { if (order == null) { throw new IllegalArgumentException("Order is null"); } // Validate and persist boolean saved = repository.save(order); return saved; }

10e. Note with JavaScript Syntax Highlighting

EventEmitter +on(event: String, callback: Function) +emit(event: String, data: Object) async function emit(event, data) { const listeners = this.listeners[event] || []; for (const fn of listeners) { await fn(data); // sequential } console.log("Done:", event); }

10f. Note with C++ Syntax Highlighting

Matrix -rows: int -cols: int +transpose(): Matrix Matrix Matrix::transpose() const { auto result = Matrix(cols, rows); for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { result(j, i) = this->at(i, j); } } return result; }

UML Sequence Diagram Tests

11. Basic Synchronous Call & Response

GET /book/id responseCode=200, book client: Client server: LibraryServer

10. Alt Fragment

ALT GET /book/id responseCode=200, book responseCode=404 client: Client server: LibraryServer [book found] [else]

11. Multiple Participants (Login Flow)

enter credentials POST /login authenticate(user, pass) findUser(user) userRecord authResult 200 OK + token show dashboard user: User browser: WebBrowser login: LoginController auth: AuthService db: UserDB

12. Loop Fragment

LOOP getItems(page) fetchItem(id) itemData itemList c: Client s: Server db: Database [for each item in page]

13. Opt Fragment (Optional)

OPT submitOrder() sendEmail(user, order) sent orderConfirmation user: User app: App notif: NotificationService [user has notifications enabled]

14. Train System Sequence (from Lecture)

press() requestStop(stationA) stopTrain() stopped openDoors() doorsOpen board pressRequestButton(stationB) requestStop(stationB) closeDoors() doorsClosed startTrain(velocity) p: Passenger btn: StationButton sys: TrainSystem train: Train doors: Doors

15. Execution Specifications (Explicit Activation)

GET /book/id SELECT * FROM books resultSet responseCode=200, book client: Client server: LibraryServer db: Database

16. Nested Activations

login(credentials) authenticate(user, pass) findUser(user) userRecord token loginSuccess user: User app: Application auth: AuthService db: UserDB

17. Self-Message

request() validate() process() response client: Client server: Server

18. Lost and Found Messages

networkEvent request() timeout response logEntry client: Client server: Server

19. Stacked Execution Specifications (Observer Pattern)

register(self) notify(someEvent) update() getData() data Observer Subject

19b. Stacked Bars — Deep Nesting

login() checkCredentials() loadProfile() profile valid session client: Client server: Server db: Database

20. Nested Fragments (Loop containing Alt)

LOOP ALT fetchAll() query(id) record transform() query(id) null logMissing() results c: Client s: Server db: Database [for each record] [found] [not found]

21. Destroy / Delete Message (Lifeline Termination)

connect() open() connection sessionId query(sql) execute(sql) resultSet results disconnect() close() bye c: Client s: Session db: Database

22. Break Fragment (Early Exit from Loop)

LOOP BREAK search(query) lookup(page) cachedResult cachedResult lookup(page) miss computePage() result c: Client s: Server cache: Cache [for each page] [cache hit]

23. Par (Parallel) Fragment

PAR placeOrder() reserveItems() reserved chargeCard() charged sendConfirmation() sent orderComplete ui: UI svc: OrderService inv: Inventory pay: PaymentGateway notif: Notifications [parallel processing] [payment] [notification]

24. Ref (Interaction Use) Fragment

REF login() authenticate(credentials) token getData(token) data showDashboard user: User app: App auth: AuthService api: API [Authentication Handshake]

25. Critical Fragment

CRITICAL withdraw(amount) debit(amount) success updateBalance() newBalance dispenseCash atm: ATM bank: BankServer acct: Account [atomic transaction]

26. Multiple Else Clauses in Alt

ALT request(type) 200 OK + data validate() 201 Created authorize() 204 No Content 405 Method Not Allowed c: Client s: Server [type == GET] [type == POST] [type == DELETE] [else]

27. Deeply Nested Fragments (3 Levels)

OPT LOOP ALT request() process() query() data query() wait() result response c: Client gw: Gateway svc: Service db: Database [authenticated] [retry up to 3 times] [success] [timeout]

28. Neg (Forbidden/Invalid) Fragment

NEG deleteAccount() DROP TABLE users error maintenanceInProgress user: User sys: System db: Database [must not happen during maintenance]

29. Async Messages and Create/Destroy Lifecycle

submitTask() create() execute(task) taskComplete result client: Client pool: ThreadPool worker: Worker

30. Sequence Diagram Notes

authenticate() findUser(token) userRecord authResult Validates JWT token Lookup by indexed token field At this point the server has verified the user identity and can proceed with authorization. c: Client s: Server db: Database

UML State Machine Diagram Tests

31. Exosuit State Machine (from SEBook)

Idle entry / initSensors() exit / logStateChange() CombatMode EmergencyPower threatNeutralized / retractWeapons() threatDetected [sysCheckOK] / deployUI() powerLevel < 5% / rerouteToLifeSupport() manualOverride() powerOn()

20. Order Lifecycle

Created Paid Shipped Delivered Cancelled Refunded refund_requested / processRefund() cancel_order [within 24hrs] delivery_confirmed payment_received Order Placed ship_order

21. Simple Turnstile

Locked Unlocked push insertCoin

22. Vending Machine with Internal Actions

Idle AcceptingMoney entry / displayPrice() do / countInsertedCoins() Dispensing entry / activateMotor() exit / stopMotor() complete / resetMachine() cancel / returnMoney() [sufficientFunds] / startDispense() selectProduct

35. State Diagram with Note

Idle Processing Done Error retry startJob [queueNotEmpty] exception complete init() Max 3 retries allowed

UML Component Diagram Tests

36. Client-Server (from Lecture)

GET Book POST Book Client LibraryServer

24. Three-Tier Architecture

uses SQL Queries HTTP Requests WebUI AppServer Database Logger

25. Microservices

sendReceipt processPayment sendConfirmation /api/users /api/orders APIGateway UserService OrderService PaymentService NotificationService

26. Frontend-Backend-Database (directional ports)

SQL publish HTTP / JSON Frontend httpOut Backend httpIn dbOut eventOut Database dbIn EventBus eventIn

27. Microservice API Gateway (Port-to-Port)

POST GET GET POST GET POST GET POST GET Gateway out1 out2 Auth in out1 out2 Users /users /users /users/unsubscribe/{userId} Clubs /clubs /clubs/roles/{clubId}/{userId} out1 /clubs/event-reference/{eventId} Events /events out1 out2 /events/template-data/{templateId} Notifications /notifications/event-update out2 out1

27b. Component API Back-Edges with Shared Ports

patch /users /unsubscribe /{userId} get /events /template-data /{templateId} delete /clubs /event-reference /{eventId} get /users get /clubs post /users get /clubs /roles /{clubId} /{userId} post /events post /notifications /event-update gateway auth users /users clubs /clubs events /events notifications /notifications

27c. Component Dashed Visual Style

report observe publish Source events Worker jobs status Monitor External Topic

27d. Standalone Labelled Ports

consume produce Publisher out Subscriber in Kafka Topic

28. Joined Assembly Interfaces (Ball-and-Socket)

OrderItems CustomerInfo Order Warehouse CRM

29. Disjoined Interfaces (Standalone Lollipop and Socket)

UserAPI DataStore WebApp Database MobileApp

40. Component Diagram with Note

SQL REST Frontend API Database All requests are authenticated via JWT middleware before reaching the handler.

UML Deployment Diagram Tests

41. Web Application Deployment

WebServer Nginx AppServer DatabaseServer PostgreSQL ClientDevice WebBrowser HTTPS TCP/IP

27. Ticket System (from UML Reference)

TicketServer TicketSeller CreditCardCharges TicketDB Kiosk CustomerInterface SalesTerminal ClerkInterface network network

28. Microservices Deployment

LoadBalancer Nginx AppNode1 UserService OrderService AppNode2 PaymentService NotificationService DataNode MongoDB Redis HTTP HTTP TCP TCP gRPC

30. Web App Deployment — Horizontal Layout

ClientDevice WebBrowser WebServer Nginx AppServer DatabaseServer PostgreSQL HTTPS TCP/IP

31. Microservices — Horizontal Layout

LoadBalancer Nginx AppNode1 UserService OrderService AppNode2 PaymentService NotificationService DataNode MongoDB Redis HTTP HTTP TCP TCP gRPC

29. Node Instance Notation (name:Type underlined, per UML spec Fig 9-3)

server:BankServer Transactions AccountMgmt client:ATMKiosk ATMSoftware network

50. Deployment Diagram with Note

LoadBalancer HAProxy AppServer NodeApp DBServer PostgreSQL HTTP TCP/5432 Encrypted at rest with AES-256

Additional UML Regression Tests

51. Enumeration (Class Diagram)

«enumeration» Color RED GREEN BLUE «enumeration» Size SMALL MEDIUM LARGE Product -name: String -color: Color -size: Size

52. Choice Pseudostate (State Machine)

Validating Approved Rejected validate() [invalid] submit [valid]

53. Actor Stick Figures (Sequence Diagram)

login(credentials) findUser(name) userRecord welcome screen user: User app: Application db: Database

54. Create Message (Sequence Diagram)

request() Handler <<create>> result response client: Client server: Server

55. Composite State (State Machine)

Active Running Paused Idle activate() resume() deactivate() shutdown() pause()

UML Use Case Diagram Tests

56. Login System (Use Case)

Auth System Log In Register Account Reset Password Manage Users Confirm Email User Admin <<extend>> <<include>>

57. Online Store (Use Case)

Online Store Browse Products Add to Cart Checkout Pay for Order Customer Payment Gateway <<include>>

Actor Inheritance — LMS with User Hierarchy

LMS Login View Course Submit Assignment Grade Submission User Student Instructor

Actor Inheritance — Hospital System

Hospital System View Patient Records Prescribe Medication Administer Treatment Schedule Appointment Authenticate Medical Staff Doctor Nurse Patient <<include>>

UML Activity Diagram Tests

58. Order Processing (Activity Diagram)

Receive Order Validate Payment Payment Valid? Process Order Reject Order Ship Order [yes] [no]

59. Login Flow (Activity Diagram)

Enter Credentials Authenticate Valid? Load Dashboard Show Error [yes] [no]

60. Swimlanes (Activity Diagram)

Customer Warehouse Shipping Place Order Pick Items Pack Ship Receive

61. Composition Crossing Test (Composite Pattern)

«abstract» Component +operation(): void +add(child: Component): void +remove(child: Component): void Leaf +operation(): void Composite -children: List<Component> +operation(): void +add(child: Component): void +remove(child: Component): void Client 1 0..* treats uniformly

61b. Association Label Direction Cues

Source Target Observer reads publishes

61c. Label Direction Cues Across Diagram Types

request Client Server
Ready Running start
call Client Gateway
Browser Server deploy
Login User starts
Run [go]

@startuml
box "A" as A
box "B" as B
A --> B : flows <
@enduml
  

62. Composition Behind Class Test (Order System)

«interface» Billable +processPayment(): bool Customer -id: int -name: String +placeOrder(): void VIP Guest Order -date: Date -status: String +calcTotal(): float LineItem -quantity: int Product -price: float -name: String 1 0..* 1..* 0..* 1

63. Composition Detour Test (Shape/Color)

«abstract» Shape -color: int +area(): double +setColor(r: int, g: int, b: int) Color -r: int -g: int -b: int Canvas +render() Logger +log(msg: str) Rectangle -width: int -length: int +setWidth(width: int) +setHeight(height: int) uses

64. Component Port Crossing Test

POST GET Notifications out1 /notifications/event-update out2 Templates ts/template-data/{templateId} out2

65. Component Port Non-Crossing Test

SQL publish Backend httpIn dbOut eventOut Database dbIn EventBus eventIn

66. Composition Behind Class (Circle/Drawing)

«interface» Serializable +serialize(): string +deserialize(data: string) «abstract» Shape #color: string +area(): number Circle -radius: number +constructor(radius: number) +area(): number +serialize(): string +deserialize(data: string) Drawing

67. Aggregation/Composition Vertical (UserService)

UserService +constructor(repo: UserRepository) +getUser(id: string): string[] UserRepository +constructor(db: Database) +findById(id: string): string[] Database +query(sql: string): string[] Cache +get(key: string): string | null +set(key: string, value: string)

68. Aggregation Detour (Priority/Task)

«enumeration» Priority +Low +Medium +High +Critical «interface» Identifiable +getId(): string «interface» Assignable +assignTo(user: string) Task -id: string -assignee: string +constructor(id: string, priority: Priority) +getId(): string +assignTo(user: string) Epic -subtasks: Task[] +addSubtask(task: Task)

69. Element Colors — Class Diagram

Plain Highlighted Warning Error Success «service» Service

70. Element Colors — State Machine

Idle Failed Done reset

71. Element Colors — Sequence Diagram

request forward query result response reply Client Gateway Service Database

72. Element Colors — Component Diagram

Frontend API Gateway Auth Service Data Service Database

73. Texture Overlays — Class Diagram

Plain Colour Hatched Crosshatch Dotted Grid Striped

74. Texture Overlays — State Machine

Draft Approved

75. Texture Overlays — Component Diagram

Legacy Module Deprecated API Active Service New Module

76. Colors and Textures — Use Case Diagram

Login View Dashboard Manage Users Generate Report User Admin

77. Colors and Textures — Deployment Diagram

"Production" "Staging" "Database WebServer AppServer Primary Replica

78. Colors and Textures — Git Graph


@startuml
branch main:
  A "Initial commit"
  B "Add auth module"
  C "Fix login bug" #FF9999
  D "Release v1.0" #99FF99 hatched

branch feature from B:
  α "Start OAuth" #lightblue
  β "Implement flow" #lightblue dotted
  γ "Tests pass" #FFEB3B crosshatch

branch hotfix from C:
  h1 "Patch CVE" #FF9999 striped

head main
@enduml
  

79. Colors and Textures — Folder Tree


@startuml
project-root/
  src/ #lightblue
    components/ #lightblue hatched
      Button.tsx #99FF99
      Modal.tsx #99FF99 dotted
    utils/
      auth.ts #FFEB3B
      helpers.ts
    deprecated/ #FF9999 crosshatch
      oldApi.ts #FF9999 striped
      legacyAuth.ts #FF9999 striped
  tests/ #lightcoral grid
    Button.test.tsx
    auth.test.ts
  README.md
  package.json #FFEB3B
@enduml
  

Venn Diagram Tests

80. Two-Set Venn (Default Palette)


@startuml
title Programming Languages

set Compiled
set "Memory Safe"

Compiled                 : C, C++
"Memory Safe"            : Python, Ruby, JavaScript
Compiled & "Memory Safe" : Rust, Go, Swift
outside                  : Assembly
@enduml
  

81. Three-Set Venn (Classic Three-Circle)


@startuml
title Web Technologies

set Frontend
set Backend
set Database

Frontend                      : React, Vue
Backend                       : Django, Rails
Database                      : PostgreSQL, Redis
Frontend & Backend            : Next.js, SvelteKit
Backend & Database            : Prisma, SQLAlchemy
Frontend & Database           : PouchDB
Frontend & Backend & Database : Firebase, Supabase
outside                       : Docker
@enduml
  

82. Four-Set Venn (All 16 Regions)


@startuml
title Developer Skills

set Frontend
set Backend
set DevOps
set Design

Frontend                                   : React, CSS
Backend                                    : APIs, SQL
DevOps                                     : Docker, K8s
Design                                     : Figma, UX
Frontend & Design                          : UI libs
Backend & DevOps                           : SRE
Frontend & Backend                         : Full-stack
DevOps & Design                            : Design ops
Frontend & Backend & DevOps                : Platform eng
Frontend & Backend & Design                : Product eng
Frontend & DevOps & Design                 : Frontend infra
Backend & DevOps & Design                  : Backend infra
Frontend & Backend & DevOps & Design       : Unicorn
@enduml
  

83. Five-Set Venn (Grünbaum Ellipses)


@startuml
title Meals

set Breakfast
set Lunch
set Dinner
set Vegetarian
set Quick

Breakfast                             : Pancakes
Lunch                                 : Club sandwich
Dinner                                : Steak
Vegetarian                            : Tofu
Quick                                 : Toast
Breakfast & Quick                     : Cereal
Lunch & Vegetarian                    : Salad
Dinner & Vegetarian                   : Risotto
Breakfast & Vegetarian & Quick        : Yogurt
Lunch & Dinner & Vegetarian           : Veggie bowl
Breakfast & Lunch & Dinner & Vegetarian & Quick : Smoothie
@enduml
  

84. Custom Colors — Contrast Detection


@startuml
title Biomes

set Ocean #0077be
set Forest #228b22
set Desert #edc9af

Ocean                   : whale, kelp
Forest                  : oak, deer
Desert                  : cactus, scorpion
Ocean & Forest          : mangrove
Forest & Desert         : savanna scrub
Ocean & Desert          : coastal dunes
Ocean & Forest & Desert : biosphere
@enduml
  

85. Custom Colors — CSS Named Colors (Light Fills)


@startuml
title Pastel Palette — Text Should Be Dark

set Alpha lightyellow
set Beta lightpink
set Gamma lightblue

Alpha                 : item1, item2
Beta                  : item3
Gamma                 : item4
Alpha & Beta          : shared ab
Alpha & Gamma         : shared ag
Beta & Gamma          : shared bg
Alpha & Beta & Gamma  : all three
@enduml
  

86. Venn with Notes on Intersections


@startuml
title Developer Skills

set Frontend
set Backend
set DevOps

Frontend                    : React
Backend                     : Django
DevOps                      : Docker
Frontend & Backend          : Next.js
Backend & DevOps            : Platform
Frontend & Backend & DevOps : SRE

note left of Frontend : Pure UI\nwork
note right of Frontend & Backend : Popular full-stack\nframeworks
note top of Frontend & Backend & DevOps : Rare but valuable
note bottom of DevOps
  Infrastructure
  specialists
end note
@enduml
  

87. Venn with Stacked Notes and Outside-Targeted Note


@startuml
title Notes Stacking

set A
set B
set C

A         : item1
B         : item2
C         : item3
A & B     : shared
outside   : leftover

note right of A     : Alpha stuff
note right of B     : Beta stuff
note right of A & B : Combined A+B
note left of outside : dropped during\ntriage
@enduml
  

88. Venn with Quoted Set Names (Spaces)


@startuml
title Programming Languages

set Compiled
set "Memory Safe"

Compiled                 : C, C++
"Memory Safe"            : Python, Ruby, JavaScript
Compiled & "Memory Safe" : Rust, Go, Swift
outside                  : Assembly
@enduml
  

ER Diagram Tests (Chen Notation)

89. Basic ER — Library System


@startuml
title Library System

entity Student {
  # student_id
  name
  email
  / age
  * phones
}

entity Book {
  # isbn
  title
  * authors
}

relationship Borrows {
  date_out
  date_due
}

Student "N" -- Borrows
Book "M" -- Borrows
@enduml
  

90. Weak Entity with Identifying Relationship


@startuml
title Employee Dependents

entity Employee {
  # emp_id
  name
  salary
}

weak entity Dependent {
  ~ dep_name
  dob
  relationship_type
}

identifying relationship Has

Employee "1" == Has
Dependent "N" == Has
@enduml
  

91. Ternary Relationship


@startuml
title University Enrolment

entity Student {
  # sid
  name
}

entity Course {
  # cid
  title
}

entity Semester {
  # term
}

relationship Enrolls {
  grade
}

Student "N" -- Enrolls
Course "M" -- Enrolls
Semester "1" -- Enrolls
@enduml
  

92. Multiple Relationships Between Entities


@startuml
title Hospital

entity Doctor {
  # doc_id
  name
  specialty
}

entity Patient {
  # pat_id
  name
  / age
}

relationship Treats {
  visit_date
}

relationship PrimaryCareOf

Doctor "N" -- Treats
Patient "M" -- Treats
Doctor "1" -- PrimaryCareOf
Patient "N" -- PrimaryCareOf
@enduml
  

93. Participation Constraints (Total vs Partial)


@startuml
title Course System

entity Course {
  # course_id
  title
}

entity Instructor {
  # inst_id
  name
}

entity Student {
  # sid
  name
}

relationship TaughtBy

relationship Takes

Course "1" == TaughtBy
Instructor "1" -- TaughtBy

Student "N" -- Takes
Course "M" == Takes
@enduml