【发布时间】:2019-05-06 17:00:18
【问题描述】:
我是 MockMVC 和 junit 的新手,所以需要帮助,所以情况是我需要模拟一个方法,同时模拟包含该方法的外部方法。例如方法calculator(int a, int b),我用两个模拟值模拟这个方法,在这个方法中有另一个方法可以做一些其他的验证(比如说一些外部验证)。
我可以模拟主方法计算器,直到调用这个外部方法,我习惯用“Given().willReturn()”模拟主方法(计算器),另一个“Given( ).willReturn()" 语句来模拟包含方法(验证之一),但这给了我 nullPointer 异常。所以我需要一些可以帮助我解决这个问题的东西,以便可以有条不紊地进行模拟。
public GuestRegistrationResponse registerGuest(SomeObject guestRegistrationRequest) throws Exception {
SomeObject guestRegistrationResponse = new SomeObject();
Folio folio = new Folio();
folio.setForename(guestRegistrationRequest.getForename());
folio.setEmail1(guestRegistrationRequest.getEmail());
folio.setCity(guestRegistrationRequest.getCity());
Result result = null;
result = (Result) sampleAPICall.executeExternalAPI(result,new Class[] { SomeObject.class, User.class, Another.class, Folio.class, FolioList.class },
Result.class);
if (result != null && result.getFolioList() != null ) {
guestRegistrationResponse.setFolioid(result.getFolioList().getFolio().getFolioId());
} else {
throw new ExternalException(result.getResult());
}
return guestRegistrationResponse;
}
测试方法
@RunWith(SpringRunner.class)
@WebMvcTest(value = ServiceImpl.class, secure = true)
public class TestServiceImpl {
@Autowired
MockMvc mockmvc;
@InjectMocks
ServiceImpl serviceImpl;
@Before
public void setUp() {
// We would need this line if we would not use MockitoJUnitRunner
MockitoAnnotations.initMocks(this);
// Initializes the JacksonTester
JacksonTester.initFields(this, new ObjectMapper());
}
@Test
public void testRegisterGuest() throws Exception {
SomeObject mockInput = new SomeObject();
mockInput.setCity("CITY");
mockInput.setEmail("test@test.com");
mockInput.setForename("FORENAME");
/* other datat is also collected*/
ExpectedResponse mockOutput = new ExpectedResponse();
mockOutput.setResult(true);
Result Result = new Result();
Result.setMessage("success");
Result.setStatus(true);
processTestThatMethod(mockInput, mockOutput, Result);
}
private void processTestThatMethod(SomeObject mockInput, ExpectedResponse mockOutput,
,Result result) throws Exception {
System.out.println("Inside processTestThatMethod");
given(serviceImpl.registerGuest(mockInput)).willReturn(mockOutput);
// what to do below ..
given(sampleAPICall.executeExternalAPI(any(Result.class),any(new Class[]{SomeObject.class, User.class, Another.class, Folio.class, FolioList.class}),any(Result.class))).willReturn(result);
}
}
已编辑代码@Sachin rai
【问题讨论】:
-
在发布代码之前至少要花一些精力来格式化代码
-
对不起 Deadpool ,它不是一个正确的代码,它只是展示逻辑的一些示例,这就是为什么将它添加为语句的原因。感谢您的投票。
-
不,我不是反对者@david
-
开个玩笑@Pool ,请不要投票的人回答我的问题,至少一个小线索或链接可以帮助我解决我的问题。 :)
标签: java spring-boot junit mockmvc