0

I am new to spring boot.

I have a Service class as below

@Service
public class AService{
    @Value("${sample.time})
    private Long time;
    ...
    public int sampleMethod(){
        ...
       return time;
     }
}

and my application.yml under src/resource has:

sample:
    time:1

and my junit test class is:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = MainApplication.class)
public class AServiceTest{
    @Autowired
   private WebApplicationContext wac;

   private Aservice aservice;

  @Before
  public void setupMockMvc() {
    MockitoAnnotations.initMocks(this);
    aservice = new AService();
    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }
  public void sampleMethodTest(){
    Assert.assertEquals(1,aservice.sampleMethod());
  }

This always gives false, because the method aservice.sampleMethod() Returns 0. It is not able to read the yml file under src when am testing. I know that since ist injected with spring by standalone like this wont work. But it would be great help if you could guide me with possible Solutions or any pointers are helpful too.

Thanks in advance

MJK
  • 3,434
  • 3
  • 32
  • 55
pgman
  • 493
  • 3
  • 12
  • 21

2 Answers2

0

You need to make your .yaml file available under /src/test/resources too in order for tests to be able to access these properties.

This will also enable you to set test specific properties.

Plog
  • 9,164
  • 5
  • 41
  • 66
0

Error is due to new AService(). remove new AService() and use autowired AService.

Try below:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@SpringBootTest(classes = MainApplication.class)
public class AServiceTest{
    @Autowired
   private WebApplicationContext wac;
    @Autowired
   private Aservice aservice;

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

    mockMvc = MockMvcBuilders.webAppContextSetup(wac).build();
  }
  public void sampleMethodTest(){
    Assert.assertEquals(1,aservice.sampleMethod());
   }
Barath
  • 5,093
  • 1
  • 17
  • 42
  • Thanks alot Bharath... This works... U saved my day...Can you Point to any links which explains about this.. – pgman Sep 12 '17 at 14:02
  • @pgman see this https://stackoverflow.com/questions/19896870/why-is-my-spring-autowired-field-null – Barath Sep 12 '17 at 14:06
  • @bharath, though this works. now if i do any Mocks using Mock... Mocks arent working. If i remove Autowired then Mocks works but noth the yaml file. Is there any configuration am missing? – pgman Sep 15 '17 at 09:23
  • i.e., when i use @Mock to mock an instance... it isnt working when autowired is used – pgman Sep 15 '17 at 09:23
  • @pgman if you use ```@Mock``` then you have to define its mocked behaviour it will never load the value – Barath Sep 15 '17 at 09:27