Komponenty najlepiej testować z frameworkami TestNG oraz Mockito, gdyż istnieją one już w projekcie systemu. TestNG służy do tworzenia kolejnych testów jednostkowych, sprawdzania warunków, inicjalizacji testów, łapania pożądanych wyjątków itp. Mockito służy natomiast do tworzenia implementacji i wstrzykiwania obiektów, które są niezbędne do przetestowania niektórych funkcjonalności (np. gdy komponent używa systemowych serwisów ProcessService, UserService itp.). Przykładowy datachooser korzystający z serwisu UserFinder:
Do tak stworzonego komponentu zostanie wstrzyknięty przez adnotację @Autowired systemowy serwis UserFinder.
Przykładowy test powyższej klasy miałby postać:
Serwis UserFinder został zmockowany przez adnotację @Mock. Statyczne metody when i thenReturn określają zachowanie się serwisu UserFinder dla konkretnych wywołań. Należy pamiętać, że nie jest to prawdziwy systemowy serwis, a jedynie tymczasowa implementacja na czas wykonywania testów. Adnotacja @InjectMocks mówi o tym, iż do stworzonego obiektu komponentu (FindingUserDataChooser) Mockito będzie próbował wstrzyknąć implementacje do jego pól (w tym przypadku wstrzyknie UserFindera). Systemowe serwisy można również wstrzykiwać w komponentach przez stworzenie oznaczonego adnotacją @Autowired konstruktora posiadającego w parametrach kolejne serwisy. Przykładowy komponent:
W takim przypadku również serwis UserFinder zostanie poprawnie zaciągnięty przez komponent. Komponent można przetestować w poniższy sposób:
|
Components are best tested with TestNG and Mockito frameworks, as they already exist in the system design. TestNG is used to create more unit tests, check conditions, initialize tests, catch desired exceptions, etc. Mockito, on the other hand, is used to create implementations and inject objects that are necessary to test some functionality (e.g. when a component uses system ProcessService, UserService, etc.). Example datachooser using UserFinder service:
The system UserFinder service will be injected into the component created in this way by the @Autowired annotation.
An example test of the above class would be:
The UserFinder service has been dockerized by the @Mock annotation. The static methods when and thenReturn determine the behavior of the UserFinder service for specific calls. Note that this is not a real system service, but only a temporary implementation for the duration of the tests. The @InjectMocks annotation says that to the created component object (FindingUserDataChooser), Mockito will try to inject implementations into its fields (in this case, it will inject UserFinder). System services can also be injected into components by creating an annotated @Autowired constructor that has further services in its parameters. Example component:
In this case, the UserFinder service will also be correctly pulled by the component. You can test the component in the following way:
|