0

I am using spring-boot-1.5. Is there any way to load application.properties in src/test/resources during the unit test? I know how to load it using integration test we can use @SpringBootTest or @ContextConfiguration but I would like to use application.properties during unit test.

Let me explain my scenario a bit,

@SpringBootApplication(exclude = { MongoAutoConfiguration.class, MongoDataAutoConfiguration.class })
@EnableHypermediaSupport(type = EnableHypermediaSupport.HypermediaType.HAL)
public class BookBackendApplication {

    public static void main(String[] args) {
        SpringApplication.run(BookBackendApplication.class, args);
    }
}

@Service
public class BookService {
    @Value("${book-list:ACTIVE}")
    private List<String> bookList = new ArrayList<>();
    @Value("${book-status:PURCHASING}")
    private String bookStatus;

    public BookResponse purchaseBook(BookRequest bookRequest) {
       if(bookRequest.getStatus().equals(bookStatus)) { //Here getting NPE while executing unit test
            ....
       }
    }
}

UNIT TEST

@RunWith(SpringRunner.class)
public class BookServiceTest {

    @InjectMocks
    private BookService bookService;

  @Test
  public void testBookActivate() throws IOException {
      BookResponse bookResponse = bookService.purchaseBook(bookRequest);
      ...
  }
}

Properties are not loading while running this unit test so getting NPE in BookService.java. Is there any way to load src/test/resource/application.properties while running the unit test?

Any pointers or help would be really appreciable.

VelNaga
  • 3,593
  • 6
  • 48
  • 82

2 Answers2

0

You can use @TestPropertySource

See this page: override-default-spring-boot-application-properties-settings-in-junit-test

applemango
  • 123
  • 1
  • 9
  • Nope it didn’t work ....I’ve already tried it ....it will work only with context configuration...for unit test you don’t require context ....Same applicable for propertyResource – VelNaga Nov 22 '18 at 01:49
0

Finally, I got an answer. I have used below code to set static fields while running mocks. ReflectionTestUtils resolved the issue.

@RunWith(SpringRunner.class)
public class BookServiceTest {

    @InjectMocks
    private BookService bookService;

    @Before
    public void setup() {
        ReflectionTestUtils.setField(bookService, "bookStatus", "PURCHASING");
        ReflectionTestUtils.setField(bookService, "bookList", Arrays.asList("ACTIVE","ACTIVATING"));
    }

  @Test
  public void testBookActivate() throws IOException {
      BookResponse bookResponse = bookService.purchaseBook(bookRequest);
      ...
  }
}

Thanks a lot for the support guys. Let's keep helping others.

VelNaga
  • 3,593
  • 6
  • 48
  • 82