1

I have a service with an attribute like this:

@Autowired
@Qualifier("test")
private String test;

This attribute come from context xml file.

I become nothing in unit test, probably that a correct behavior in unit test. But can I mock this attribute to become a value?

for example:

when(test).thenReturn("a string"); 

Thanks Regards

anubis
  • 1,425
  • 5
  • 18
  • 47
  • Does [this](https://stackoverflow.com/q/19682293/3890673) help? – crusy Apr 09 '19 at 11:27
  • I not see if that can be helping. Even if I make my String test public... – anubis Apr 09 '19 at 11:33
  • Why are y ou autowiring a String? That should come from a property file.Generally defining simple things like strings/integers as beans isn't a wise thing to do. – M. Deinum Apr 09 '19 at 11:43
  • 1
    There are a couple of answer under that link (plus some explanation why private autowired fields may cause trouble); I tried to answer the most common ones below. @m-deinum: A String is a perfectly reasonable type of bean, even if it comes from a property file – crusy Apr 09 '19 at 11:52

1 Answers1

1

Based on your comment making the field public is an option. You can just set it afterwards:

myMock = Mock(MyClass)
myMock.test = "foobar"

Besides that you could add a setter, leaving the field private. Or you could try @InjectMocks or Spring's ReflectionTestUtils, both from the accepted answer here.

crusy
  • 1,424
  • 2
  • 25
  • 54
  • I don't understand because I have already tested, but that works fine with ReflectionTestUtils. Thanks you – anubis Apr 09 '19 at 11:55