- Java測(cè)試框架介紹
java有很多測(cè)試類框架, 開(kāi)發(fā)中有很多比如Mokito, powermock, wiremock, cucumber ,但是powermock測(cè)試,sonar不認(rèn)其覆蓋率.
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
以下所有的例子以下圖為依據(jù)皆辽, 寫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'
}
// 遇到以下錯(cuò)誤需要導(dǎo)入
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 用來(lái)mock 獨(dú)立沒(méi)有依賴的類
@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方法被執(zhí)行了一次
用來(lái)測(cè)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測(cè)試框架的一個(gè)工具, 能夠測(cè)試組件與組件之間的API調(diào)用, service里API的測(cè)試
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/
本文由博客群發(fā)一文多發(fā)等運(yùn)營(yíng)工具平臺(tái) OpenWrite 發(fā)布