【问题标题】:spring-boot junit load test property resource for unit test用于单元测试的 spring-boot junit 负载测试属性资源
【发布时间】:2019-04-24 15:34:15
【问题描述】:

我正在使用 spring-boot-1.5。 单元测试期间有没有办法在src/test/resources中加载application.properties?我知道如何使用集成测试来加载它,我们可以使用 @SpringBootTest 或 @ContextConfiguration 但我想在单元测试期间使用 application.properties。

让我解释一下我的场景,

@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
            ....
       }
    }
}

单元测试

@RunWith(SpringRunner.class)
public class BookServiceTest {

    @InjectMocks
    private BookService bookService;

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

运行此单元测试时未加载属性,因此在 BookService.java 中获取 NPE。运行单元测试时有什么方法可以加载 src/test/resource/application.properties 吗?

任何指点或帮助都会非常可观。

【问题讨论】:

    标签: java spring unit-testing spring-boot junit


    【解决方案1】:

    你可以使用@TestPropertySource

    查看此页面:override-default-spring-boot-application-properties-settings-in-junit-test

    【讨论】:

    • 不,它没有工作......我已经尝试过了......它只适用于上下文配置......对于单元测试,你不需要上下文...... .同样适用于propertyResource
    【解决方案2】:

    终于,我得到了答案。我在运行模拟时使用下面的代码来设置静态字段。 ReflectionTestUtils 解决了这个问题。

    @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);
          ...
      }
    }
    

    非常感谢大家的支持。让我们继续帮助他人。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 2023-04-10
      • 2019-04-26
      • 2021-05-17
      • 2018-07-19
      • 2019-03-09
      • 2019-10-26
      • 2016-05-28
      相关资源
      最近更新 更多