Основной метод ServerApp имеет метод для инициализации службы. Он отлично работает при запуске внутри IDE, но не запускается при запуске интеграционного теста. Как заставить тест работать? Что еще можно улучшить в тесте?
ServerApp
@SpringBootApplication
@EnableConfigurationProperties({LiquibaseProperties.class, ApplicationProperties.class})
public class ServerApp {
@PostConstruct
public void initApplication() {
//...
}
public static void main(String[] args) {
SpringApplication app = new SpringApplication(ServerApp.class);
DefaultProfileUtil.addDefaultProfile(app);
applicationContext = app.run(args);
Environment env = applicationContext.getEnvironment();
//...
applicationContext.getBean(BalanceService.class).init(); // <<< this one
}
Тест
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK, classes = ServerApp.class)
@AutoConfigureMockMvc
public class BalanceResourceIntTest {
private static final String DEFAULT_USERNAME = "playerTEST";
private static final UUID TRANSACTION_UUID_ONE = UUID.fromString("336ca9de-1583-4f39-9c67-f8380323d09d");
private static final UUID TRANSACTION_UUID_TWO = UUID.fromString("4a14ca32-a952-11e8-98d0-529269fb1459");
private static final BigDecimal INITIAL_BALANCE = new BigDecimal(3);
private static final BigDecimal BALANCE_CHANGE = new BigDecimal(2);
private static final BigDecimal BALANCE_AFTER_CHANGE = new BigDecimal(5);
private static final Long DEFAULT_BALANCE_VERSION = 1L;
private static final Long UPDATED_BALANCE_VERSION = 2L;
private final Logger log = LoggerFactory.getLogger(BalanceResourceIntTest.class);
@Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
@Autowired
private ExceptionTranslator exceptionTranslator;
@Autowired
private PageableHandlerMethodArgumentResolver pageableArgumentResolver;
@Autowired
private EntityManager em;
@Autowired
private TransactionService transactionService;
@Autowired
private PlayerRepository playerRepository;
private MockMvc restBalanceMockMvc;
private Player player;
private Transaction transaction;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
final BalanceResource balanceResource = new BalanceResource(transactionService);
this.restBalanceMockMvc = MockMvcBuilders.standaloneSetup(balanceResource)
.setCustomArgumentResolvers(pageableArgumentResolver)
.setControllerAdvice(exceptionTranslator)
.setConversionService(createFormattingConversionService())
.setMessageConverters(jacksonMessageConverter).build();
}
public static Transaction createTransaction() {
Transaction transaction = new Transaction();
transaction.setUsername(DEFAULT_USERNAME);
transaction.setTransactionId(TRANSACTION_UUID_ONE);
transaction.setBalanceChange(BALANCE_CHANGE);
return transaction;
}
public static Player createEntity(EntityManager em) {
Player player = new Player()
.username(DEFAULT_USERNAME)
.balanceVersion(DEFAULT_BALANCE_VERSION)
.balance(INITIAL_BALANCE);
return player;
}
@Before
public void initTest() {
player = createEntity(em);
transaction = createTransaction();
}
@Test
@Transactional
public void updatePlayer() throws Exception {
playerRepository.saveAndFlush(player);
int databaseSizeBeforeUpdate = playerRepository.findAll().size();
// Update the player
log.debug("transaction: {}", transaction);
restBalanceMockMvc.perform(put("/api/balance")
.contentType(TestUtil.APPLICATION_JSON_UTF8)
.content(TestUtil.convertObjectToJsonBytes(transaction)))
.andExpect(status().isOk())
.andExpect(jsonPath("$.[*].transactionId").value(hasItem(TRANSACTION_UUID_ONE)))
.andExpect(jsonPath("$.[*].errorCode").value(hasItem("")))
.andExpect(jsonPath("$.[*].balanceVersion").value(hasItem(UPDATED_BALANCE_VERSION.intValue())))
.andExpect(jsonPath("$.[*].balanceChange").value(hasItem(BALANCE_CHANGE))) // intValue?
.andExpect(jsonPath("$.[*].balance").value(hasItem(BALANCE_AFTER_CHANGE.intValue())));
Thread.sleep(BalanceService.INIT_DELAY_OF_SCHEDULER + BalanceService.DELAY_BETWEEN_SCHEDULED_JOBS);
// Validate the Player in the database
List<Player> playerList = playerRepository.findAll();
assertThat(playerList).hasSize(databaseSizeBeforeUpdate);
Player testPlayer = playerList.get(playerList.size() - 1);
assertThat(testPlayer.getUsername()).isEqualTo(DEFAULT_USERNAME);
assertThat(testPlayer.getBalanceVersion()).isEqualTo(UPDATED_BALANCE_VERSION);
assertThat(testPlayer.getBalance()).isEqualTo(BALANCE_AFTER_CHANGE);
}
}
Тест не пройден с:
java.lang.AssertionError: Status
Expected :200
Actual :500
В консоли нет отладочной информации, которая вызывает ошибку 500 на стороне сервера.