![](/img/trans.png)
[英]Can I use Assert class in Junit if I am not implementing Junit test cases and how to do that?
[英]How can I use strings to describe test cases in Java?
使用JUnit,我的測試用例的描述通常在方法名稱中,例如:
@Test
public void should_return_6_if_distance_is_2km() {
}
要么
@Test
public void shouldReturn6IfDistanceIs2km() {
}
這不是很可讀。
但是,通過其他語言的測試框架(例如javascript或scala),我可以使用:
describe("Taximeter") {
it("should return 6 if the distance is 2km") {
...
}
}
使用純字符串更容易理解。
用Java可以做到嗎?
JUnit中的assert方法允許您執行類似的操作。 您可以執行以下操作:
assertTrue("Should return 6 if the distance is 2km but returned " + myvar, myvar == 6);
這樣可以使您的代碼可讀,但僅在不滿足預期條件時才返回一條消息。
頻譜非常接近我的要求:
@RunWith(Spectrum.class)
public class ExampleSpec {{
describe("A spec", () -> {
final int foo = 1;
it("is just a code block with a run() method", new Block() {
@Override
public void run() throws Throwable {
assertEquals(1, foo);
}
});
it("can also be a lambda function, which is a lot prettier", () -> {
assertEquals(1, foo);
});
it("can use any assertion library you like", () -> {
org.junit.Assert.assertEquals(1, foo);
org.hamcrest.MatcherAssert.assertThat(true, is(true));
});
describe("nested inside a second describe", () -> {
final int bar = 1;
it("can reference both scopes as needed", () -> {
assertThat(bar, is(equalTo(foo)));
});
});
it("can have `it`s and `describe`s in any order", () -> {
assertThat(foo, is(1));
});
});
}
不確定Scala-Part,這僅僅是描述還是可運行的Testcode?
如果描述:有關可讀但可自動化的Testcase-Description,請查看黃瓜( https://cucumber.io )或jBehave( http://jbehave.org )
如果代碼可運行:可以嘗試使Testcase自身的代碼更具可讀性( https://code.google.com/p/hamcrest/wiki/Tutorial )。
用Mockito框架編寫的單元測試非常易讀。 這些文檔承諾可以“編寫更具可讀性的漂亮測試”,並“產生清晰的驗證錯誤”。親自體驗一下:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Mockito.eq;
@RunWith(MockitoJUnitRunner.class)
public class UserServiceTest {
@Mock
private UserRepository userRepositoryMock;
@InjectMocks
private UserService userService = new UserService();
@Test
public void testLoadUserByUsername() {
// Expected objects
User demoUser = new User("user", "demo", "ROLE_USER");
// Mockito expectations
when(userRepositoryMock.findByUsername("user")).thenReturn(demoUser);
// Execute the method being tested
User userDetails = userService.loadUserByUsername("user");
// Validation
assertThat(userDetails.getUsername(), eq("user"));
verify(userRepositoryMock).findByUsername("user");
}
}
要使Mockito與Maven一起使用,應使用以下依賴項:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.8.47</version>
<scope>test</scope>
</dependency>
並使Mockito與Gradle一起使用時,應使用以下依賴項:
dependencies { testCompile "org.mockito:mockito-core:2.+" }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.