1+ using System . Text ;
2+ using Microsoft . Extensions . ObjectPool ;
3+ using Sidio . OpenGraph . ObjectPooling ;
4+
5+ namespace Sidio . OpenGraph . Tests . ObjectPooling ;
6+
7+ public sealed class StringBuilderPolicyTests
8+ {
9+ [ Fact ]
10+ public void Create_ShouldReturnNewInstance ( )
11+ {
12+ // Arrange
13+ const int Capacity = 20 ;
14+ var policy = new StringBuilderPolicy ( Capacity ) ;
15+
16+ // Act
17+ var result = policy . Create ( ) ;
18+
19+ // Assert
20+ result . Should ( ) . NotBeNull ( ) ;
21+ result . Length . Should ( ) . Be ( 0 ) ;
22+ result . Capacity . Should ( ) . Be ( Capacity ) ;
23+ }
24+
25+ [ Fact ]
26+ public void Return_ShouldClearStringBuilder ( )
27+ {
28+ // Arrange
29+ var policy = new StringBuilderPolicy ( ) ;
30+ var stringBuilder = policy . Create ( ) ;
31+ stringBuilder . Append ( "Test" ) ;
32+
33+ // Act
34+ var result = policy . Return ( stringBuilder ) ;
35+
36+ // Assert
37+ stringBuilder . Length . Should ( ) . Be ( 0 ) ;
38+ result . Should ( ) . BeTrue ( ) ;
39+ }
40+
41+ [ Fact ]
42+ public void Return_WhenCapacityExceeded_DiscardStringBuilder ( )
43+ {
44+ // Arrange
45+ const int MaxCapacity = 100 ;
46+ var policy = new StringBuilderPolicy ( 10 , MaxCapacity ) ;
47+ var stringBuilder = policy . Create ( ) ;
48+ stringBuilder . Append ( 'a' , MaxCapacity + 1 ) ;
49+
50+ // Act
51+ var result = policy . Return ( stringBuilder ) ;
52+
53+ // Assert
54+ result . Should ( ) . BeFalse ( ) ;
55+ }
56+
57+ [ Fact ]
58+ public void Pool_WhenCapacityNotExceeded_UsesPolicyCorrectly ( )
59+ {
60+ // Arrange
61+ var pool = new DefaultObjectPool < StringBuilder > ( new StringBuilderPolicy ( ) ) ;
62+
63+ // Act
64+ var sb1 = pool . Get ( ) ;
65+ sb1 . Append ( "Hello" ) ;
66+ pool . Return ( sb1 ) ;
67+
68+ var sb2 = pool . Get ( ) ; // should be same instance but cleared
69+
70+ // Assert
71+ sb1 . Should ( ) . BeSameAs ( sb2 ) ;
72+ sb2 . Length . Should ( ) . Be ( 0 ) ;
73+ }
74+
75+ [ Fact ]
76+ public void Pool_WhenCapacityExceeded_UsesPolicyCorrectly ( )
77+ {
78+ // Arrange
79+ const int MaxCapacity = 100 ;
80+ var pool = new DefaultObjectPool < StringBuilder > ( new StringBuilderPolicy ( 10 , MaxCapacity ) ) ;
81+
82+ // Act
83+ var sb1 = pool . Get ( ) ;
84+ sb1 . Append ( 'a' , MaxCapacity + 1 ) ;
85+ pool . Return ( sb1 ) ;
86+
87+ var sb2 = pool . Get ( ) ; // should be new instance
88+
89+ // Assert
90+ sb1 . Should ( ) . NotBeSameAs ( sb2 ) ;
91+ sb2 . Length . Should ( ) . Be ( 0 ) ;
92+ }
93+ }
0 commit comments