簡體   English   中英

測試 Spring bean 時模擬配置屬性

[英]Mocking a configuration property when testing a Spring bean

我有一個 Spring bean,它從application.yml讀取配置屬性值

public class AutoDisableRolesService {

    @Value("${cron.enabled}")
    private boolean runTask;
    // remainder of class omitted
}

在 application.yml 中,此屬性設置為 false

cron:
  enabled: false

但是當我運行測試時,我希望它是真的。 我嘗試了以下方法,但似乎不起作用

@SpringBootTest(properties = { "cron.enabled=true" })
@ExtendWith(MockitoExtension.class)
public class AutoDisableRolesServiceTests {
    
    @Mock
    private UserRoleRepository userRoleRepository;

    @InjectMocks
    private AutoDisableRolesService autoDisableRolesService;
    // remainder of test class omitted
}

我也嘗試了以下方法,但沒有成功

@ContextConfiguration(classes = AutoDisableRolesService.class)
@TestPropertySource(properties = "cron.enabled=true")
@ExtendWith(MockitoExtension.class)
public class AutoDisableRolesServiceTests {

    @Mock
    private UserRoleRepository userRoleRepository;

    @InjectMocks
    private AutoDisableRolesService autoDisableRolesService;
    // remainder of test class omitted
}

您正在混合兩種類型的測試設置; 帶有 Mockito 測試設置的 Spring 啟動測試設置。 通過在被測類上使用@InjectMocks ,Mockito 實例化該類並注入所有用@Mock注釋的字段,繞過 Spring TestApplicationContext 設置。

使用以下方法設置 Spring 測試:

@SpringBootTest(properties = { "cron.enabled=true" })
public class AutoDisableRolesServiceTests {
    
    @MockBean
    private UserRoleRepository userRoleRepository;

    @Autowired
    private AutoDisableRolesService autoDisableRolesService;

    // remainder of test class omitted
}

或使用以下方法設置的 mockito:

public class AutoDisableRolesServiceTests {
    
    @Mock
    private UserRoleRepository userRoleRepository;

    @InjectMocks
    private AutoDisableRolesService autoDisableRolesService;

    @BeforeEach
    public void setUp() {
        ReflectionTestUtils.setField(autoDisableRolesService, "runTask", true);
    }
}

[編輯]

如果您不需要完整的 @SpringBootTest 設置,請使用

@ExtendWith(SpringExtension.class)
@TestPropertySource(properties={"cron.enabled=true"})
@ContextConfiguration(classes = { AutoDisableRolesService.class})
public class AutoDisableRolesServiceTests {
    
    @MockBean
    private UserRoleRepository userRoleRepository;

    @Autowired
    private AutoDisableRolesService autoDisableRolesService;

    // remainder of test class omitted
}

@SpringBootTest 和@ExtendsWith(SpringExtension.class) 之間的區別在於@SpringBootTest 加載完整的(測試)ApplicationContext,而后者只加載部分上下文,這更快但不包括所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM