1

I have a @ConfigurationProperties class like this:

@ConfigurationProperties(prefix = "myprops", ignoreUnknownFields = false) @Configuration public class MyProperties { private Long mySchedulerRate; @Bean public Long mySchedulerRate() { return this.mySchedulerRate; } } 

I'm registering it as a bean so I can refer to it in an annotation for a Spring scheduler:

@Scheduled(fixedRateString = "#{@mySchedulerRate}") public void runScheduledUpdate() { ... { 

However, I now want to write a unit test where I want to be able to set a different value for the bean 'mySchedulerRate'. Mocking/Spying on the @ConfigurationProperties class doesnt seem to work since the scheduler gets set up before the stubbing has been set to return my desired value.

What is the easiest way to achieve what I am trying to do?

7
  • what exactly u want to test? according to the code above mySchedulerRate has nothing expect for a Long value Commented Nov 17, 2017 at 16:08
  • I want the value of that Long bean to be different in one particular test so I was trying to change the value of the bean. What Im trying to test isnt super relevant to the issue. Commented Nov 17, 2017 at 16:09
  • try to declare this value in application.properties under test folder. so that when u test, that value will be taken Commented Nov 17, 2017 at 16:10
  • Yeah but I want it to only be different for this one particular test and all the others I want it to be something else. Commented Nov 17, 2017 at 16:12
  • Is it a test with a Spring runner or a Mockito runner ? Showing your actual test would be a good start. Commented Nov 17, 2017 at 16:14

1 Answer 1

3

Managed to fix this now. I was running a @SpringBootTest and I realise you can override properties here within the annotation for a particular test class.

This worked for me:

@RunWith(SpringRunner.class) @SpringBootTest(classes = MyApp.class, properties = "myprops.my-scheduler-rate=1000") public class MyTest { 

So no need to try and override the bean, I was overcomplicating this far too much.

Sign up to request clarification or add additional context in comments.

3 Comments

I waited for your answer to propose this way if you used a Spring Runner. Finally, you found it alone fast :) Great
Its not usual for me to give up and ask SO but I was banging my head until just now! Bit late on a Friday for me I think. I'll try repay you for your time anyway :)
Sometimes, the light comes a little late :) You are kind. Anyway, good answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.