Java 在Spring中用一个Mock,What I';我做错了?
我有一个SpringBoot项目,其中我有控制器、服务和映射器层。现在我想测试一个服务,并模拟映射程序。我是这样做的: 测试:Java 在Spring中用一个Mock,What I';我做错了?,java,spring,unit-testing,mocking,Java,Spring,Unit Testing,Mocking,我有一个SpringBoot项目,其中我有控制器、服务和映射器层。现在我想测试一个服务,并模拟映射程序。我是这样做的: 测试: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(Application.class) @Transactional public class SomeServiceTest extends AbstractTransactionalJUnit4SpringContextT
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(Application.class)
@Transactional
public class SomeServiceTest extends AbstractTransactionalJUnit4SpringContextTests {
@Mock
private AMapper aMapper;
@Autowired
@InjectMocks
AService aService;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
executeSqlScript("classpath:insertSomeData.sql", false);
}
@Test
public void testMethod() throws Exception {
//prepareSomeData
aService.callMethod(someData);
verify(aMapper).callTheRightMethod(rightObject);
}
以及服务:
@Service
@Transactional(readOnly = true)
public class AServiceImpl implements AService {
@Autowired
BMapper bMapper;
@Autowired
CMapper cMapper;
@Override
@Transactional(readOnly = false)
public SomeReturnObject callMethod(SomeData someData)throws Exception {
//some execution to obtain aResult
if(true){
aMapper.callTheRightMethod(aResult);}
else
aMapper.callWrongMethod(aResult);
}
现在,当我执行测试时,结果是:
Wanted but not invoked:
aMapper.callTheRightMethod{..}
Actually, there were zero interactions with this mock.
当我调试时,我看到调用了该方法,但可能是错误的映射程序(不是模拟的)。你有一些解决这个问题的技巧吗?我在这里看不到模拟交互录音。它应该在实际调用之前出现。应该是这样的
Mockito.when(aMapper.callTheRightMethod(Mockito.any()).thenReturn(rightObject);
流程应该是这样的。首先记录模拟,然后执行实际调用,最后验证模拟交互。如上所述,测试类不需要Autowire。请把它也拿走。而是通过将一些数据传递给服务类的构造函数来创建服务类的新实例。希望这有帮助。快乐编码 我不太明白为什么要启动spring上下文来测试一个服务层一次只测试一层。 这就是我解决问题的方法。(如果有什么东西不符合我的要求,我道歉..从头开始写)
从
SomeServiceTest
中的aService
中删除@Autowired
,它会工作的。是的,这帮助我找出了问题并解决了它。TanksI必须为其他映射程序制作这个,但不是为我将检查方法调用的那个映射程序。坦克:)
@RunWith(MockitoJUnit4ClassRunner.class)
public class SomeServiceTest {
@Mock
private AMapper aMapper;
@InjectMocks
AService aService = new AService();
@Test
public void testMethod() throws Exception {
// given
Mockito.doReturn(aResult).when(aMapper).getAResult();
// when
aService.callMethod(someData);
// then
verify(aMapper).callTheRightMethod(rightObject);
}