我是模拟Junit测试的新手。这是我要测试的主要课程: import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.springframework.stereotype.Component;
@Component
public class IlinqChecksumCalculator {
private static Logger DATA_LOADER_CHECKSUM_CALCULATOR_LOGGER = Logger.getLogger(IlinqChecksumCalculator.class);
public String calculateCheckSum(String rfsdata) throws IOException {
System.out.println(rfsdata);
String checkSumValue = null;
if (StringUtils.isNotBlank(rfsdata)) {
try {
// Create MessageDigest object for MD5
MessageDigest digest = MessageDigest.getInstance("MD5");
// Update input string in message digest
digest.update(rfsdata.getBytes(), 0, rfsdata.getBytes().length);
// Converts message digest value in base 16 (hex)
checkSumValue = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException exception) {
DATA_LOADER_CHECKSUM_CALCULATOR_LOGGER.error(
"Error in determineInputCheckSum() method during calculation of checksum for Input JSON String for ",
exception);
}
}
System.out.println("Final checksum value is:" + checkSumValue);
return checkSumValue;
}
}
这是我的测试班:
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.when;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockitoAnnotations;
import org.mockito.runners.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class)
public class IlinqChecksumCalculatorTest {
private IlinqChecksumCalculator ilinqCheckSum;
@Before
public void setUp() throws Throwable {
MockitoAnnotations.initMocks(this);
}
@Test
public void testCheckSum() throws IOException {
when(ilinqCheckSum.calculateCheckSum("abcde")).thenReturn("defgh");
assertEquals("defgh", ilinqCheckSum.calculateCheckSum("abcde"));
}
}
我收到空指针异常。
答案 0 :(得分:0)
回答你的问题:要将ilinqCheckSum
作为模拟处理,你应该用@Mock
注释它。
但在这里你不应该使用mockito!你想测试IlinqChecksumCalculator
而不是模拟!您应该创建它的真实实例,并在必要时将依赖关系注入模拟。
答案 1 :(得分:0)
通过模拟calculateCheckSum方法,您不会覆盖单元测试中的任何代码。我想你不应该在这里使用Mock。尝试以下测试方法。
public void testCheckSum() throws IOException {
String result = ilinqCheckSum.calculateCheckSum("abcde")
assertNotNull(result );
}