【发布时间】:2020-05-05 06:40:23
【问题描述】:
我认为我的问题与这个问题有关: Tests pass when run individually but not when the whole test class run
我的测试都单独通过,但是当我运行测试类时,其中两个失败了。调试表明 assertEquals 期望的状态与代码中给出的不同,主要是来自不同测试的状态。解决方案应该使用 @Before 或 @After 并进行清理,但我在使用时遇到了麻烦,因为实例是从 Spring 自动装配的。
主要问题:我的想法是否正确以及如何“重置”自动装配的实例?
@SpringBootTest
class StatementProcessorServiceTest {
@Autowired
StatementProcessorService statementProcessorService;
private StatementProcessorInputModel setup(long id, boolean endbalanceCorrect) {
StatementProcessorInputModel statementProcessorInputModel = new StatementProcessorInputModel();
statementProcessorInputModel.startBalance = 1.00;
statementProcessorInputModel.id= id;
statementProcessorInputModel.startBalance = 1.00;
statementProcessorInputModel.mutation = 1.00;
statementProcessorInputModel.endBalance = endbalanceCorrect ? 2.00 : 1.00;
return statementProcessorInputModel;
}
@Test
void verify_with_all_good_settings()
{
StatementProcessorResponseModel sut;
sut = statementProcessorService.validate(setup(1, true));
Assert.assertEquals(sut.result, "SUCCESSFUL");
}
@Test
void verify_with_good_settings_but_duplicated_reference()
{
StatementProcessorResponseModel sutFirst = statementProcessorService.validate(setup(2, true));
Assert.assertEquals(sutFirst.result, "SUCCESSFUL");
StatementProcessorResponseModel sutSecond;
sutSecond = statementProcessorService.validate(setup(2, true));
Assert.assertEquals(sutSecond.result, "DUPLICATE_REFERENCE");
}
@Test
void verify_with_wrong_endBalance_and_good_reference()
{
StatementProcessorResponseModel sut = statementProcessorService.validate(setup(3, false));
Assert.assertEquals(sut.result, "INCORRECT_END_BALANCE");
}
@Test
void verify_with_all_wrong_settings()
{
StatementProcessorResponseModel sutFirst = statementProcessorService.validate(setup(4, true));
Assert.assertEquals(sutFirst.result, "SUCCESSFUL");
StatementProcessorResponseModel sutSecond = statementProcessorService.validate(setup(4, false));
Assert.assertEquals(sutSecond.result, "DUPLICATE_REFERENCE_INCORRECT_END_BALANCE");
}
}
编辑 1:添加服务代码
@Component
public class StatementProcessorService {
private StatementProcessorResponseModel responseModel = new StatementProcessorResponseModel();
private static ArrayList<Long> usedReferences = new ArrayList<>();
public StatementProcessorResponseModel validate(StatementProcessorInputModel inputModel){
if(!validateUniqueReference(inputModel.transactionReference))
{
responseModel.errorRecords.add("account_number_of_ inCorrectEndBalance _record");
responseModel.result = "DUPLICATE_REFERENCE";
}
if(!validateMutation(inputModel))
{
responseModel.errorRecords.add("account_number_of_ inCorrectEndBalance _record");
if (!responseModel.result.isBlank()){
responseModel.result = responseModel.result + "_INCORRECT_END_BALANCE";
}
else{
responseModel.result = "INCORRECT_END_BALANCE";
}
}
if (responseModel.result.isBlank()){
responseModel.result = "SUCCESSFUL";
}
return responseModel;
}
【问题讨论】:
标签: java spring junit spring-boot-test