If you are using swi-prolog
See: with_output_to/2
Note: with_output_to/2 is implemented using C in SWI-Prolog so is not portable as Prolog code.
?- with_output_to(string(Output),(write('hello'),write('Rusian'),write('!'))),
assertion( Output == "helloRusian!").
With corrections to your code and using SWI-Prolog unit tests
greeting(Name) :-
write('hello'),
write(Name),
writeln('!').
:- begin_tests(your_tests).
test(001, Output == 'helloMoncho!\n') :-
with_output_to(atom(Output), greeting('Moncho')).
:- end_tests(your_tests).