gpt4 book ai didi

java - 如何模拟 @InjectMocks 类中的方法?

转载 作者:行者123 更新时间:2023-11-30 01:46:34 27 4
gpt4 key购买 nike

我正在 Spring Mvc 上使用 Mockito 进行 JUnit 测试。测试使用 @InjectMock 和 @Mock 以及when(method(..)).thenReturn(X)。问题是如何@Mock @Inject 实例中的方法?

我尝试创建两个实例,例如@InjectMocksFoo fooInstance 和 @Mock Foo fooInstanceMock;我的思维方式是区分注入(inject)什么实例和模拟什么。我还尝试将 Spy 与 InjectMocks 一起使用,但它返回异常。

实际类语法-

class Foo {
public X(..) {
...
Y(...); // method call to Y
...
}

public Y(..) {
...
}
}

测试语法 -

public class FooTest {
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}

@InjectMocks
Foo fooInstance;

@Mock
Foo fooInstanceMock;

@Test
public void xTest{
when(fooInstanceMock.Y(..)).thenReturn(true);
Boolean result = fooInstance.X(25);
Assert.assertTrue(result == true)
}
}

当返回 true 时,我将输出排除为 true,但因为它认为它是一个jectMock 并且它进入实现。

最佳答案

@InjectMocks 用于将您在测试中定义的模拟注入(inject)到带有此注释的非模拟实例中。

在您的用例中,您似乎正在尝试做一些不同的事情 - 您想要一个 Foo 的真实实例以及 x 的真实实现,但是模拟 x 调用的 y 的实现。这可以通过部分模拟来完成,或者用 Mockito 的术语来说,监视:

public class FooTest{

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

// Default constructor is used to create a real Foo instance.
// In the test's body, though, we'll override the behavior of SOME of the methods
@Spy
Foo fooInstance;

@Test
public void xTest {
doReturn(true).when(fooInstance).y(/* arguments, presumably 25 */);
Boolean result = fooInstance.x(25);
Assert.assertTrue(result);
}
}

关于java - 如何模拟 @InjectMocks 类中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57724801/

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