我怎样才能对bean进行部分模拟

Sna*_*ake 1 java spring mockito

我有以下 JUNIT 课程

@RunWith(SpringJUnit4ClassRunner.class)
@Configuration
@ContextConfiguration(locations = { "classpath:junit-xxx.xml", "classpath:junit-xxxxx.xml" })
public class TestFictionalClass
{

@Autowired   // I changed this to @Mock so the first "when" below works
private MyService mService


@Before
    @Transactional
    public void setUp() throws Exception {
         MockitoAnnotations.initMocks(this);

         Mockito.when((mService).myMockedMethod(Mockito.any(String.class)))
        .thenReturn("Hello");

        Mockito.when((mService).myOtherRealMethod(Mockito.any(BigDecimal.class), Mockito.any(BigDecimal.class))).thenCallRealMethod();

}
Run Code Online (Sandbox Code Playgroud)

我在这里尝试做的是模拟其中一个方法,因此它始终返回值“hello”,但我希望类中的其他方法正常执行。问题我在第二种方法中遇到以下错误

org.mockito.exceptions.base.MockitoException:无法在java对象上调用抽象真实方法!仅当模拟非抽象方法时才可以调用真实方法。

如何模拟有问题的类,以便覆盖它的方法之一返回的值?

谢谢

PS:我正在使用 Mockito 和 Spring MVC

ams*_*ger 5

使用 @Spy 注释代替 @Mock。间谍活动提供了仅模拟特定方法(使用“何时-那么”)并让其他方法按原样工作的方法。

有关间谍活动的更多信息:链接