I'm trying to run some unit tests on some Data objects that I use in Spring.
I set up my unit test like this:
@ExtendWith(SpringExtension.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(
locations = "classpath:application.properties")
@JdbcTest
public class TestInventory {
@Autowired
DataSource dataSource;
@Test
public void testFinishedGoods() throws SQLException {
....
}
}
I'm getting an error because in one of my Data Objects I access a cache like this:
var ctx = ApplicationContextProvider.getApplicationContext();
CacheRepository cacheRepository = ctx.getBean(CacheRepository.class);
Currency currencyObj = cacheRepository.getCurrencyList().stream().filter(cur -> cur.identity() == currency).findFirst().orElseThrow();
currencyRate = currencyObj.rate();
This works fine in the web app, but in JInit I get:
java.lang.NullPointerException: Cannot invoke ".springframework.context.ApplicationContext.getBean(java.lang.Class)" because "ctx" is null
I implemented ApplicationContextProvider as ApplicationContextAware which works fine. Only JUnit has a problem.
Any ideas?
I'm trying to run some unit tests on some Data objects that I use in Spring.
I set up my unit test like this:
@ExtendWith(SpringExtension.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(
locations = "classpath:application.properties")
@JdbcTest
public class TestInventory {
@Autowired
DataSource dataSource;
@Test
public void testFinishedGoods() throws SQLException {
....
}
}
I'm getting an error because in one of my Data Objects I access a cache like this:
var ctx = ApplicationContextProvider.getApplicationContext();
CacheRepository cacheRepository = ctx.getBean(CacheRepository.class);
Currency currencyObj = cacheRepository.getCurrencyList().stream().filter(cur -> cur.identity() == currency).findFirst().orElseThrow();
currencyRate = currencyObj.rate();
This works fine in the web app, but in JInit I get:
java.lang.NullPointerException: Cannot invoke ".springframework.context.ApplicationContext.getBean(java.lang.Class)" because "ctx" is null
I implemented ApplicationContextProvider as ApplicationContextAware which works fine. Only JUnit has a problem.
Any ideas?
Share edited Mar 8 at 10:03 Mark Rotteveel 110k229 gold badges156 silver badges224 bronze badges asked Mar 7 at 17:43 sproketboysproketboy 9,47718 gold badges68 silver badges100 bronze badges2 Answers
Reset to default 0I solved it by removing @JdbcTest and then added
@SpringBootTest(classes = MyApplication.class)
The final set of annotations I used:
@ExtendWith(SpringExtension.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@TestPropertySource(locations = "classpath:application.properties")
@ContextConfiguration(classes = TestInventory.class)
@SpringBootTest(classes = MyMainApplication.class)
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744914966a4600778.html
评论列表(0条)