gpt4 book ai didi

java - 让反射在单元测试中工作的问题

转载 作者:行者123 更新时间:2023-12-02 01:01:39 25 4
gpt4 key购买 nike

我正在尝试运行单元测试用例,但无法让反射正常工作。我的 testSubject 使用供应商类来获取 map 。供应商类有一个 Autowiring 的 modulusChecker,我试图用反射来设置它。但是,每当我运行测试时,doubleAlterneteModulusChecker 都会设置为 null?

package uk.co.cdl.account.bankdetailsvalidation.api.impl;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.Arrays;
import java.util.Collection;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.read.ListAppender;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.InjectMocks;
import org.mockito.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.slf4j.LoggerFactory;
import org.springframework.test.util.ReflectionTestUtils;

import uk.co.cdl.account.bankdetailsvalidation.model.BankDetailsValidationModel;
import uk.co.cdl.account.bankdetailsvalidation.moduluschecker.DoubleAlternateModulusChecker;
import uk.co.cdl.account.bankdetailsvalidation.supplier.ModulusCheckerMapSupplier;
import uk.co.cdl.account.bankdetailsvalidation.supplier.ModulusWeightTableSupplier;
import uk.co.cdl.account.bankdetailsvalidation.supplier.SortCodeSubstitutionTableSupplier;

@ExtendWith(MockitoExtension.class)
@DisplayName("CDLBankDetailsValidator Unit Tests")
class CDLBankDetailsValidatorTest {

@Spy
private DoubleAlternateModulusChecker doubleAlternateModulusChecker;

@Spy
private ModulusCheckerMapSupplier modulusCheckerMapSupplier;

@Spy
private ValidationExceptionRuleFactory validationExceptionRuleFactory;

@Spy
private SortCodeSubstitutionTableSupplier sortCodeSubstitutionTableSupplier;

@Spy
private ModulusWeightTableSupplier mockModulusTableSupplier;

@InjectMocks
private BankDetailsValidator testSubject;

@DisplayName("validate() returns a BankDetailsValidationModel with the correct values for a given bank account number / sort code")
@ParameterizedTest(name = "{3}" )
@MethodSource("bankAccountDetailsTestData")
void testCDLValidatorWithTestData(String sortCode, String accountNumber, BankDetailsValidationModel expected, String testDescription){
ReflectionTestUtils.setField(modulusCheckerMapSupplier, "doubleAlternateModulusChecker", doubleAlternateModulusChecker);

//then
assertEquals(expected, testSubject.validate(accountNumber, sortCode));
}

@DisplayName("Logger captures the correct debug messages")
@ParameterizedTest(name="Logged: {2}")
@MethodSource("loggerTestData")
void testLoggerCapturesDebugMessages(String sortCode, String accountNumber, String expected, int index){
//Given
ListAppender<ILoggingEvent> listAppender = getListAppender();

//When
testSubject.validate(accountNumber, sortCode);
String actual = listAppender.list.get(index).toString();

//Then
assertEquals(expected, actual);
}

private ListAppender<ILoggingEvent> getListAppender(){
Logger logger = (Logger) LoggerFactory.getLogger(CDLBankDetailsValidator.class);
ListAppender<ILoggingEvent>listAppender = new ListAppender<>();
listAppender.start();
logger.addAppender(listAppender);
return listAppender;
}
}

@Component
public class ModulusCheckerMapSupplier implements Supplier<Map> {

@Autowired
private DoubleAlternateModulusChecker doubleAlternateModulusChecker;

@Override
public Map get() {
Map<String, StandardModulusChecker> modulusChecksByAlgorithmName = new HashMap<>();
modulusChecksByAlgorithmName.put(DBLAL, doubleAlternateModulusChecker);
modulusChecksByAlgorithmName.put(MOD10, new StandardModulusChecker(10));
modulusChecksByAlgorithmName.put(MOD11, new StandardModulusChecker(11));
return modulusChecksByAlgorithmName;
}
}

@Component
public class DoubleAlternateModulusChecker extends StandardModulusChecker {
private static Logger LOGGER = LogManager.getLogger(DoubleAlternateModulusChecker.class);

@Override
public String getName() {
return "Double alternate modulus check";
}

@Override
public int getRemainder(String data, int[] weights) {
return 1;
}
}

最佳答案

您标记@Spy:

@Spy
private DoubleAlternateModulusChecker doubleAlternateModulusChecker;

但不提供初始化 => Null。

如果你想监视真实的bean实例,请使用 spring @SpyBean

如果您无权访问该注释,则使用反射:

@Autowired
private DoubleAlternateModulusChecker doubleAlternateModulusChecker;

@Autowired
private BankDetailsValidator testSubject; // Important, not @InjectMock

然后在您的测试中:

DoubleAlternateModulusChecker spy = Mockito.spy(doubleAlternateModulusChecker);
ReflectionTestUtils.setField(modulusCheckerMapSupplier, "doubleAlternateModulusChecker", spy);

关于java - 让反射在单元测试中工作的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60563766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com