【发布时间】:2020-01-29 18:56:06
【问题描述】:
在以下测试代码 sn-p 中,未从配置文件中获取 number_of_days.last 和 number_of_months.plan 的值。请检查并查看可能是什么原因。当我从服务类中删除 @Value 注释时ShiftPlanService.java 并用所需的值初始化那里的值,测试通过。
@ExtendWith(MockitoExtension.class)
@ContextConfiguration(classes=SpringbootMysqlExampleApplication.class)
@TestPropertySource(locations="src/main/resources/application.properties",properties= {"number_of_days.last= 7","number_of_months.plan= 2"})
class ShiftPlanServiceTest {
@Mock
ShiftPlanRepo mockedSpr;
@Mock(lenient = true)
ShiftDetailsRepo mockedSdr;
@Mock(lenient = true)
EmployeeDetailsRepo mockedEdr;
@Spy
ShiftPlanService sps;
@BeforeEach
public void setUp() {
when(mockedSdr.findShiftNameById(1)).thenReturn("Morning");
when(mockedSdr.findShiftNameById(2)).thenReturn("Afternoon");
when(mockedEdr.getNameById(0)).thenReturn("Amit");
when(mockedEdr.getNameById(1)).thenReturn("Anupam");
when(mockedEdr.getNameById(2)).thenReturn("Chirag");
when(mockedEdr.getNameById(3)).thenReturn("Rashmi");
when(mockedEdr.count()).thenReturn(4L);
}
@Test
public void testCreateShiftPlan() {
sps.createShiftPlan(4, 1, 2020);
verify(mockedSpr, times(36)).save(any(ShiftPlan.class));
verifyNoMoreInteractions(mockedSpr);
}
}
application.properties 文件如下-
server.port=8104
number_of_days.last= 7
number_of_months.plan= 2
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/shiftplannerdatabase
spring.datasource.username=root
spring.datasource.password=WILLsuc95#
#Keep the connection alive while idle for a long time
spring.datasource.testWhileIdle= true
spring.datasource.validationQuery= SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update)
spring.jpa.hibernate.ddl-auto = update
# Naming strategy
spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
# Use spring.jpa.properties.* for Hibernate native properties (the prefix is
# stripped before adding them to the entity manager)
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
在 ShiftPlanService 类中,我有
@Value("${number_of_days.last}")
public int ndl;
@Value("${number_of_months.plan}")
public int nm;
【问题讨论】:
标签: spring-boot mockito junit5