专栏首页CoffeeLandJava测试框架推荐
原创

Java测试框架推荐

一个好的,稳健的系统, 是函数经过数次稳健的UT测试, API和Service之间是经过BDD测试的

Java测试框架介绍

java有很多测试类框架, 开发中有很多比如Mokito, powermock, wiremock, cucumber ,但是powermock测试,sonar不认其覆盖率.

Mockito

What is mock

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

From <https://stackoverflow.com/questions/2665812/what-is-mocking>

以下所有的例子以下图为依据, 写UserImp的UT UserImplTest

Import mockito

//build.gradlew
repositories { jcenter() }
dependencies { 
	testCompile "org.mockito:mockito-core:2.+" 
	// https://mvnrepository.com/artifact/org.powermock/powermock-module-junit4
	testCompile group: 'org.powermock', name: 'powermock-module-junit4', version: '2.0.2'
	
	}


// 遇到以下错误需要导入

java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker (alternate: null)

	at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:74)
	at com.sun.proxy.$Proxy8.isTypeMockable(Unknown Source)
	at org.mockito.internal.util.MockUtil.typeMockabilityOf(MockUtil.java:29)
	at org.mockito.internal.util.MockCreationValidator.validateType(MockCreationValidator.java:22)
	at org.mockito.internal.creation.MockSettingsImpl.validatedSettings(MockSettingsImpl.java:240)
	at org.mockito.internal.creation.MockSettingsImpl.build(MockSettingsImpl.java:228)
	at org.mockito.internal.MockitoCore.mock(MockitoCore.java:61)
	at org.mockito.Mockito.mock(Mockito.java:1908)

Mock and injectMock

@Mock 用来mock 独立没有依赖的类
@InjectMock 用于去mock有依赖的类
For dependent classes, we used mocks.
From <https://howtodoinjava.com/mockito/mockito-mock-injectmocks/> 


import com.kaifei.model.User;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.List;

public class UserImplTest {

    @Mock
    UserHandler userHandler;

    @InjectMocks
    UserImpl userImpl;

    @Before
    public void before()
    {
        //Initializes objects annotated with Mockito annotations for given testClass: @Mock, @Spy, @Captor, @InjectMocks
        //See examples in javadoc for MockitoAnnotations class.
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void testGetAllUser()
    {
        //given
        User james = new User("james", 23);
        ArrayList<User> objects = new ArrayList<>();
        objects.add(james);
        Mockito.when(userHandler.getAll()).thenReturn(objects);

        //when
        List<User> actUsers = userImpl.getaAllUsers();

        //then
        Assert.assertEquals("get all done!", objects, actUsers);
    }

}

mock方法的返回值

 Mockito.when(sharingDataHandler.createSharingData()).thenReturn(sharingUuid);

Mock方法被执行了一次

用来测void方法

    @Test
    public void testCreateUser200()
    {
        //given
        User james = new User("james", 23);

        //when
        userImpl.creatUser(james);

        //then verify the UserHandler::createUser was executed only once
        Mockito.verify(userHandler, Mockito.times(1)).createUser(james);
    }

Mock throw exception

@Test(expected = NullPointerException.class)
    public void testCreatUser()
    {
        //given
        User james = new User("james", 23);
        
        //when
        userImpl.creatUser(james);
        
        //then
        //catch NullPointerException exception
    }

RabbitMQ clear Message

  @Autowired
 private MessageCollector messageCollector;
@After("@CleanAllMessages")
 public final void cleanAllMessages()
 {
 try
 {
 mockMvc.perform(
 delete("/messages/").contentType(MediaType.APPLICATION_JSON_UTF8_VALUE).content("[]"));
 messageCollector.forChannel(messageSource.statusmessageChannel()).clear();
 }
 catch (Exception e)
 {
 throw new CucumberException("Stopped at \"user invokes root cleanAllMessages:\"", e);
 }
 }

Cucumber

cucum是BDD测试框架的一个工具, 能够测试组件与组件之间的API调用, service里API的测试

https://cloud.tencent.com/developer/article/1628939

WireMock

Mock your APIs for fast, robust and comprehensive testing
WireMock is a simulator for HTTP-based APIs. Some might consider it a service virtualization tool or a mock server.

It enables you to stay productive when an API you depend on doesn't exist or isn't complete. It supports testing of edge cases and failure modes that the real API won't reliably produce. And because it's fast it can reduce your build time from hours down to minutes.

wireMock site

http://wiremock.org/

References

原创声明,本文系作者授权云+社区发表,未经许可,不得转载。

如有侵权,请联系 yunjia_community@tencent.com 删除。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • java 源代码里的failure mode

    fail-fast: java对于使用iterator迭代器来遍历集合元素时, 对同时使用集合的add/remove修改集合元素, 这样由于集合用自身的方法修改...

    CoffeeLand
  • linux内核之socket

    linux的空间分为kernel space 和 user space, 比例是1:3

    CoffeeLand
  • Stack Stracture

    Because stack是Last in first out. 因此数组的index是0最适合做栈底, 因为变化最小

    CoffeeLand
  • 基于权限安全框架Shiro的登录验证功能实现

    目前在企业级项目里做权限安全方面喜欢使用Apache开源的Shiro框架或者Spring框架的子框架Spring Security。

    用户1208223
  • 作业调度框架Quartz

    版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。

    奋飛
  • SpringBoot入门建站全系列(十五)内置定时任务及Quartz定时任务使用

    2.ScheduledExecutorService,线程池版的TimerTask。

    品茗IT
  • SpringBoot入门建站全系列(十五)内置定时任务及Quartz定时任务使用

    2.ScheduledExecutorService,线程池版的TimerTask。

    品茗IT
  • 大厂程序员为了更好的满足历史数据的保存和检索往往选择这种神操作!

    ElasticSearch是一款开源的非常火爆的文档索引引擎, 大小公司都比较青睐的一款做日志检索、分析、查询的工具。

    云存储
  • shiro + MD5

    用户5927264
  • 手写类似dubbo的rpc框架第三章《rpc框架》

    案例介绍 结合上面两章节,本章将实现rpc的基础功能;提供一给rpc中间件jar给生产端和服务端。 技术点; 1、注册中心,生产者在启动的时候需要将本地接口发布...

    小傅哥

扫码关注云+社区

领取腾讯云代金券