gpt4 book ai didi

java - 模拟某些调用,但不要在同一个 spring 服务方法中模拟某些调用

转载 作者:行者123 更新时间:2023-12-01 09:57:48 27 4
gpt4 key购买 nike

我需要为我的 spring 服务编写测试。我必须在我的服务方法中模拟一些调用,并且某些调用必须正常工作。

也就是说,我的服务方式是

myInjectingService.submit()

在服务中的该方法内,要模拟的内容是

myMockService.createSomething(.....)
myMockService.verifyP(.)

不需要模拟的是将值保存到数据库。因此,在服务中,存储库将自动连接并保存它。

我的问题是模拟不起作用。是否可以同时 mock 某事而不做某事

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/context.xml" })
@WebAppConfiguration
@ActiveProfiles("test")
class Test {
@Mock
public MyMockService myMockService;

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

@InjectMocks
private MyInjectingService myInjectingService;

@Autowired private Repository1 repository1;
@Autowired private Repository2 repository2;

static {
System.setProperty("spring.profiles.active", "test");
}

private void saveTestData() {
//create entity objects
Entity1 e1 = new Entity1();
//set attributes

//create entity objects
Entity2 e2 = new Entity2();
//set attributes

//save entity objects
repository1.save(e1);
repository2.save(e2);
}

@Test
public void submitTest() {
saveData();

P p= new P();
Mockito.when(myMockService.createSomething(Mockito.any(),Mockito.any(),Mockito.any(),Mockito.any(),Mockito.any())).thenReturn(p);
Mockito.when(myMockService.verifyP(p)).thenReturn(1);

Response res = myInjectingService.submit();
assertNotNull(res);
}
}

最佳答案

您可以尝试@SpydoCallRealMethod()

@Spy 
private Repository1 repository1;
@Before
public void setUp() throws Throwable {
MockitoAnnotations.initMocks(this);
}

stub 将如下所示:

doCallRealMethod().when(repository1).doSomething1(); //real method will be called
when(repository1.doSoemthing2()).thenReturn(somethingToReturn); //will return somethingToReturn

关于java - 模拟某些调用,但不要在同一个 spring 服务方法中模拟某些调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37043184/

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