java unit test moke_Unit Test Spring-boot Rest Controller

There is another option called, @EnableWebMvc / mockMvc through which you can test your controller layer.

Code snippet given below,

* * The TransactionsControllerTest class implements Junit functionality that * simply connect to the controller layer (TransactionsController) and test the * controller layer with some pre-defined/test value. This class also provides * the details result for each test cases. * * @author Sibsankar Bera * @version 1.0 * @since 2018-08-31 */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { TransactionsController.class, AppConfig.class, AppInitializer.class }) @EnableWebMvc public class TransactionsControllerTest { private static final Logger logger = Logger.getLogger(TransactionsControllerTest.class.getName()); private MockMvc mockMvc = null; String values = null;

@InjectMocks

private WebApplicationContext wac;

/**

* This Junit test method assigns required resources value before use.

*/

@Before

public void setup() throws Exception {

values = TransactionConstant.AUTHORIZATION_CODE;

mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();

}

/**

* This Junit test method is used to test controller layer api,

* "/transactions/getAllTransactionList"

*/

@Test

public void getAllTransactionList_Test() {

try {

logger.info("Logger Name: getAllTransactionList_Test() :: " + logger.getName());

ObjectMapper mapper = new ObjectMapper();

MvcResult result = mockMvc.perform(get("/getAllTransactionList").header("authorization_code", values))

.andReturn();

JsonNode root = mapper.readTree(result.getResponse().getContentAsString());

JsonNode resultNodes = root.path("result");

logger.debug("Junit Response :: resultNodes :: getAllTransactionList_Test() :: " + resultNodes.asText());

assertEquals(resultNodes.asText(), "success");

} catch (Exception e) {

logger.error("Junit :: Exception :: getAllTransactionList_Test() :: ", e);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值