1+ using FluentAssertions ;
2+ using libplctag . NativeImport ;
3+ using Moq ;
4+ using System ;
5+ using System . Net ;
6+ using System . Runtime . InteropServices ;
7+ using Xunit ;
8+
9+ namespace libplctag . Tests
10+ {
11+ public class TagTests : IDisposable
12+ {
13+ private const int TimeoutInMilliSeconds = 1000 ;
14+ private readonly MockRepository _mockRepository ;
15+ private readonly Mock < INative > _iNativeMock ;
16+ private readonly Tag _underTest ;
17+
18+
19+ public TagTests ( )
20+ {
21+ _mockRepository = new MockRepository ( MockBehavior . Strict ) ;
22+ _iNativeMock = _mockRepository . Create < INative > ( ) ;
23+ _underTest = new Tag ( _iNativeMock . Object ) ;
24+ _underTest . Timeout = TimeSpan . FromMilliseconds ( TimeoutInMilliSeconds ) ;
25+ }
26+
27+ [ Fact ]
28+ public void TagCanBeInitialized ( )
29+ {
30+ // ARRANGE
31+ int nativeTagHandle = 1 ;
32+ GivenTagCanBeInitializedWithHandle ( nativeTagHandle ) ;
33+
34+ // ACT
35+ _underTest . Initialize ( ) ;
36+
37+
38+ // ASSERT
39+ _underTest . IsInitialized . Should ( ) . BeTrue ( ) ;
40+ _underTest . NativeTagHandle . Should ( ) . Be ( nativeTagHandle ) ;
41+ }
42+
43+ private void GivenTagCanBeInitializedWithHandle ( int nativeTagHandle )
44+ {
45+ _iNativeMock . Setup ( native => native . plc_tag_create_ex (
46+ It . IsAny < string > ( ) ,
47+ It . IsAny < plctag . callback_func_ex > ( ) ,
48+ IntPtr . Zero ,
49+ TimeoutInMilliSeconds ) )
50+ . Returns ( nativeTagHandle ) ;
51+ }
52+
53+
54+ [ Fact ]
55+ public void TagForMyUdtShouldReturnMockedValue ( )
56+ {
57+ // ARRANGE
58+ int nativeTagHandle = 1 ;
59+ MyUdt expectedValue = new ( ) { intField = 1 , shortField = 2 } ;
60+ _underTest . ElementSize = Marshal . SizeOf ( typeof ( MyUdt ) ) ;
61+
62+ GivenTagCanBeInitializedWithHandle ( nativeTagHandle ) ;
63+ GivenMarshalledDataIsReturnedInBuffer ( nativeTagHandle , expectedValue ) ;
64+
65+ // ACT
66+ _underTest . Initialize ( ) ;
67+ MyUdt currentTagValue = _underTest . GetValue < MyUdt > ( ) ;
68+
69+ // ASSERT
70+ currentTagValue . Should ( ) . Be ( expectedValue ) ;
71+ }
72+
73+ private void GivenMarshalledDataIsReturnedInBuffer < T > ( int nativeTagHandle , T expectedData ) where T : struct
74+ {
75+ byte [ ] byteData = expectedData . ToByteArray ( ) ;
76+ int size = Marshal . SizeOf ( typeof ( T ) ) ;
77+
78+ _iNativeMock . Setup ( native => native . plc_tag_get_size ( nativeTagHandle ) ) . Returns ( size ) ;
79+ _iNativeMock . Setup ( native => native . plc_tag_get_raw_bytes ( nativeTagHandle , 0 , It . IsAny < byte [ ] > ( ) , size ) )
80+ . Returns ( ( int ) Status . Ok )
81+ . Callback ( ( int tag , int start_offset , byte [ ] buffer , int buffer_length ) =>
82+ {
83+ Array . Copy ( byteData , buffer , byteData . Length ) ;
84+ } ) ;
85+ }
86+
87+
88+ public void Dispose ( )
89+ {
90+ _mockRepository . VerifyAll ( ) ;
91+ GC . SuppressFinalize ( this ) ;
92+ }
93+ }
94+ }
0 commit comments