我是Mockito的初学者并尝试测试以下课程。
@Service
public class MyService {
public static final Logger logger = LoggerFactory.getLogger(MyService.class);
ObjectMapper objectMapper = new ObjectMapper();
public void logData(String personData) throws IOException{
Person person = objectMapper.readValue(personData, Person.class);
// log info
logger.info("log person: {}, {}", person.getName(), person.getAge());
}
}
以下是我的测试类,我试图测试是否调用ObjectMapper的readValue方法。
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
public static final Logger logger = LoggerFactory.getLogger(MyServiceTest.class);
ObjectMapper objectMapper = mock(ObjectMapper.class);
MyService myService = new MyService();
@Test
public void verifyCallToReadValue() throws IOException{
String personData = "{\"Name\":\"debieA\",\"Age\":\"31\"}";
myService.logData(personData);
verify(objectMapper, times(1)).readValue(personData, Person.class);
}
}
我得到的错误是“通缉但未调用通缉但未调用: objectMapper.readValue(......);“
如何解决此问题?
答案 0 :(得分:0)
必须将ObjectMapper
模拟作为依赖注入MyService
。
永远不要像使用MyService(new
)那样使用ObjectMapper objectMapper = new ObjectMapper()
在类本身内创建类的依赖项!
请注意我的代码中的注释和更改:
@Service
public class MyService {
public static final Logger logger = LoggerFactory.getLogger(MyService.class);
//ObjectMapper objectMapper = new ObjectMapper(); //never do that
//instead init the field in the constructor using an external dependency
private ObjectMapper objectMapper;
public MyService(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public void logData(String personData) throws IOException{
Person person = objectMapper.readValue(personData, Person.class);
// log info
logger.info("log person: {}, {}", person.getName(), person.getAge());
}
}
然后在测试中
@RunWith(MockitoJUnitRunner.class)
public class MyServiceTest {
public static final Logger logger = LoggerFactory.getLogger(MyServiceTest.class);
ObjectMapper objectMapper = mock(ObjectMapper.class);
@Test
public void verifyCallToReadValue() throws IOException{
MyService myService = new MyService(objectMapper);
// here you have to mock the readValue method. Something like this:
//when(objectMapper.readValue(...)).thenReturn(new Person());
String personData = "{\"Name\":\"debieA\",\"Age\":\"31\"}";
myService.logData(personData);
verify(objectMapper, times(1)).readValue(personData, Person.class);
}
}
答案 1 :(得分:0)
使用@Spy注释,间谍很聪明地打电话
@Spy
ObjectMapper objectMapper = new ObjectMapper();
MyService myService = new MyService();
@Test
public void verifyCallToReadValue() throws IOException{
String personData = "{\"Name\":\"debieA\",\"Age\":\"31\"}";
myService.logData(personData);
verify(objectMapper, times(1)).readValue(personData, Person.class);
}
}