ahmet burak
ahmet burak

Reputation: 13

inject bean with real parameters with mockito

I'm trying to write a unit test case with mockito and I want to inject a bean with real parameters not mocked ones.

That bean has some string values that read from a .properties file.

@Component
public class SomeParameters {

    @Value("${use.queue}")
    private String useQueue;

 }

@RunWith(MockitoJUnitRunner.class)
public class ServiceTest {

    @Mock
    private A a;

    @Autowired
    private SomeParameters someParameters;

    @Before
    public void init() {
        MockitoAnnotations.initMocks(this);

    }

    @Test
    public void testMethod() {
        if(someParameters.getUseQueue==true){
            //do something
        }else{
            /bla bla
        }
    }

my main objective is to run a test case with real scenarios. I don't want to use mock values.

I was able to inject bean with real parameters in this way. But this is the unit test case, not an integration test. So I should not give applicationContext. Can you guide me how can handle this situation?

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContextTest.xml"})
public class ServiceTest {

Upvotes: 1

Views: 1676

Answers (2)

Dharisi Suresh
Dharisi Suresh

Reputation: 150

If you want to use real properties, then load the property file using Properties object and mock the value by getting from Properties object.

Upvotes: 0

borino
borino

Reputation: 1750

If you want to use a spring-context then you should create a configuration (via xml or java config) for your test and declare only the beans that you require. For Example

For setting properties just declare @TestPropertiesSource("use.queue=someValue") otherwise you need to read value from test resources.

PS. also check @MockBean and @SpyBean especially @SpyBean

Upvotes: 1

Related Questions