Best junit code snippet using org.hamcrest.CoreMatchers.anyOf
Source: JUnitMatchers.java
1package com.txt.hamcrest;2import static org.hamcrest.CoreMatchers.allOf;3import static org.hamcrest.CoreMatchers.anyOf;4import static org.hamcrest.CoreMatchers.anything;5import static org.hamcrest.CoreMatchers.containsString;6import static org.hamcrest.CoreMatchers.describedAs;7import static org.hamcrest.CoreMatchers.endsWith;8import static org.hamcrest.CoreMatchers.equalTo;9import static org.hamcrest.CoreMatchers.instanceOf;10import static org.hamcrest.CoreMatchers.is;11import static org.hamcrest.CoreMatchers.notNullValue;12import static org.hamcrest.CoreMatchers.nullValue;13import static org.hamcrest.CoreMatchers.startsWith;14import static org.hamcrest.MatcherAssert.assertThat;15import static org.hamcrest.Matchers.equalToIgnoringCase;16import static org.hamcrest.Matchers.equalToIgnoringWhiteSpace;17import static org.hamcrest.Matchers.hasToString;18import static org.hamcrest.core.IsNot.not;19import java.util.Calendar;20import java.util.Locale;21import org.hamcrest.core.IsAnything;22import org.hamcrest.core.IsNot;23import org.hamcrest.core.IsSame;24import org.junit.Test;25class Today {26 /**27 * Provide the day of the week of today's date.28 * 29 * @return Integer representing today's day of the week, corresponding to static fields defined in Calendar class.30 */31 public int getTodayDayOfWeek() {32 return Calendar.getInstance(Locale.US).get(Calendar.DAY_OF_WEEK);33 }34}35public class JUnitMatchers {36 // Is method checks two values are equal or not. If they are equal it returns true!37 @Test38 public void isMatcherTest() {39 assertThat("txt", is("txt"));40 assertThat(true, is(true));41 assertThat(2019, is(2019));42 }43 // IsNot method checks two values are equal or not. If they are not equal it returns true!44 @Test45 public void isnotMatcherTest() {46 assertThat("txt.com", is(not("txt")));47 }48 // IsEqual method checks given objects equality.49 @Test50 public void isEqualMatcherTest() {51 assertThat("txt", equalTo("txt"));52 //assertThat("txt", describedAs("NOT EQUAL", equalTo("tsxt")));53 54 assertThat("txt", is(equalTo("txt")));55 }56 // IsNot method creates a matcher that wraps an existing matcher, but inverts the logic by which it will match.57 @Test58 public void isNotMatcherTest() {59 assertThat("txt", not(equalTo("Java")));60 assertThat("txt", is(not(equalTo("Java"))));61 }62 // EqualToIgnoringCase creates a matcher that matches if examined object is equals ignore case.63 @Test64 public void equalToIgnoringCaseTest() {65 assertThat("txt", equalToIgnoringCase("txT"));66 }67 // EqualToIgnoringCase creates a matcher that matches if examined object is equals ignore case.68 @Test69 public void equalToIgnoringWhiteSpaceTest() {70 assertThat("txt abc", equalToIgnoringWhiteSpace(" TXT abc "));71 }72 // IsNull creates a matcher that matches if examined object is null.73 @Test74 public void isNullMatcherTest() {75 assertThat(null, is(nullValue()));76 assertThat("txt", is(notNullValue()));77 }78 // HasToString creates a matcher that matches if examined object is has To String.79 @Test80 public void hasToStringTest() {81 assertThat(4, hasToString("4"));82 assertThat(3.14, hasToString(containsString(".")));83 }84 // AllOf method creates a matcher that matches if the examined object matches ALL of the specified matchers.85 @Test86 public void allOfMatcherTest() {87 assertThat("txt.com", allOf(startsWith("txt"), containsString("xt."), endsWith(".com")));88 }89 // AnyOf method creates a matcher that matches if the examined object matches ANY of the specified matchers.90 @Test91 public void anyOfMatcherTest() {92 assertThat("txt", anyOf(startsWith("txt"), containsString(".com")));93 final Today instance = new Today();94 final int todayDayOfWeek = instance.getTodayDayOfWeek();95 assertThat(todayDayOfWeek,96 describedAs("Day of week is not in range",97 anyOf(is(Calendar.SUNDAY), is(Calendar.MONDAY), is(Calendar.TUESDAY), is(Calendar.WEDNESDAY),98 is(Calendar.THURSDAY), is(Calendar.FRIDAY), is(Calendar.SATURDAY))));99 }100 // IsInstanceOf method creates a matcher that matches when the examined object101 // is an instance of the specified type, as determined by calling the102 // Class.isInstance(Object) method on that type, passing the the examined object.103 @Test104 public void isInstanceOfMatcherTest() {105 assertThat(new JUnitMatchers(), instanceOf(JUnitMatchers.class));106 }107 // IsSame method creates a matcher that matches only when the108 // examined object is the same instance as the specified target object.109 @Test110 public void isSameMatcherTest() {111 String str1 = "txt";...
Source: HamcrestMatchersTest.java
...20 */21package com.manning.junitbook.ch02.hamcrest;22import org.junit.jupiter.api.DisplayName;23import org.junit.jupiter.api.Test;24import static org.hamcrest.CoreMatchers.anyOf;25import static org.hamcrest.CoreMatchers.allOf;26import static org.hamcrest.CoreMatchers.is;27import static org.hamcrest.CoreMatchers.notNullValue;28import static org.hamcrest.CoreMatchers.nullValue;29import static org.hamcrest.Matchers.*;30import static org.hamcrest.MatcherAssert.assertThat;31public class HamcrestMatchersTest {32 private static String FIRST_NAME = "John";33 private static String LAST_NAME = "Smith";34 private static Customer customer = new Customer(FIRST_NAME, LAST_NAME);35 @Test36 @DisplayName("Hamcrest is, anyOf, allOf")37 public void testHamcrestIs() {38 int price1 = 1, price2 = 1, price3 = 2;39 assertThat(1, is(price1));40 assertThat(1, anyOf(is(price2), is(price3)));41 assertThat(1, allOf(is(price1), is(price2)));42 }43 @Test44 @DisplayName("Null expected")45 void testNull() {46 assertThat(null, nullValue());47 }48 @Test49 @DisplayName("Object expected")50 void testNotNull() {51 assertThat(customer, notNullValue());52 }53 @Test54 @DisplayName("Check correct customer properties")...
Source: AssertThatTest.java
1package com.packtpub.junit.recap;2import static org.hamcrest.CoreMatchers.allOf;3import static org.hamcrest.CoreMatchers.anyOf;4import static org.hamcrest.CoreMatchers.both;5import static org.hamcrest.CoreMatchers.containsString;6import static org.hamcrest.CoreMatchers.either;7import static org.hamcrest.CoreMatchers.endsWith;8import static org.hamcrest.CoreMatchers.equalTo;9import static org.hamcrest.CoreMatchers.hasItem;10import static org.hamcrest.CoreMatchers.hasItems;11import static org.hamcrest.CoreMatchers.is;12import static org.hamcrest.CoreMatchers.not;13import static org.hamcrest.CoreMatchers.startsWith;14import static org.hamcrest.MatcherAssert.assertThat;15import static com.packtpub.junit.recap.LessThanOrEqual.lessThanOrEqual;16import java.util.Arrays;17import java.util.List;18import org.junit.Test;;19public class AssertThatTest {20 @Test21 public void verifyMatcherValues() {22 int age = 30;23 assertThat(age, equalTo(30));24 assertThat(age, is(30));25 assertThat(age, not(equalTo(33)));26 assertThat(age, is(not(33)));27 }28 @Test29 public void verifyMultipleValues() {30 double marks = 100.00;31 assertThat(marks, either(is(100.00)).or(is(90.9)));32 assertThat(marks, both(not(99.99)).and(not(60.00)));33 assertThat(marks, anyOf(is(100.00), is(1.00), is(55.00), is(88.00), is(67.8)));34 assertThat(marks, not(anyOf(is(0.00), is(200.00))));35 assertThat(marks, not(allOf(is(1.00), is(100.00), is(30.00))));36 }37 38 @Test39 public void verifyCollectionValues() {40 List<Double> salary = Arrays.asList(50.0,200.0,500.0);41 assertThat(salary, hasItem(500.0));42 assertThat(salary, hasItems(500.0,50.0));43 assertThat(salary, not(hasItem(500.3)));44 }45 46 @Test47 public void verifyStrings() {48 String name = "John Jr Dale";...
Source: AssertionsShowTest.java
1package com.airhacks;2import java.util.Arrays;3import java.util.List;4import static org.hamcrest.CoreMatchers.allOf;5import static org.hamcrest.CoreMatchers.anyOf;6import static org.hamcrest.CoreMatchers.both;7import static org.hamcrest.CoreMatchers.containsString;8import static org.hamcrest.CoreMatchers.either;9import static org.hamcrest.CoreMatchers.everyItem;10import static org.hamcrest.CoreMatchers.hasItem;11import static org.hamcrest.CoreMatchers.hasItems;12import static org.hamcrest.CoreMatchers.not;13import org.hamcrest.CustomMatcher;14import org.hamcrest.Matcher;15import static org.junit.Assert.assertThat;16import org.junit.Before;17import org.junit.Test;18/**19 *20 * @author airhacks.com21 */22public class AssertionsShowTest {23 private List<String> stringList;24 @Before25 public void init() {26 this.stringList = Arrays.asList("java", "javaee", "joker");27 }28 @Test29 public void lists() {30 assertThat(stringList, hasItem("java"));31 assertThat(stringList, hasItem("javaee"));32 assertThat(stringList, hasItems("javaee", "joker"));33 assertThat(stringList, everyItem(containsString("j")));34 }35 @Test36 public void combinableMathers() {37 assertThat(stringList, both(hasItem("java")).and(hasItem("javaee")));38 assertThat(stringList, either(hasItem("java")).or(hasItem("javascript")));39 assertThat(stringList, anyOf(hasItem("javascript"), hasItem("javaee")));40 assertThat(stringList, allOf(hasItem("java"), not(hasItem("erlang"))));41 }42 @Test43 public void customMatcher() {44 Matcher<String> containsJ = new CustomMatcher<String>("contains j") {45 @Override46 public boolean matches(Object item) {47 if (!(item instanceof String)) {48 return false;49 }50 String content = (String) item;51 return content.contains("j");52 }53 };...
Source: HamcrestTests.java
1package hamcrestTests;2import static org.hamcrest.CoreMatchers.allOf;3import static org.hamcrest.CoreMatchers.anyOf;4import static org.hamcrest.CoreMatchers.containsString;5import static org.hamcrest.CoreMatchers.equalTo;6import static org.hamcrest.CoreMatchers.is;7import static org.hamcrest.number.OrderingComparison.greaterThan;8import static org.hamcrest.number.OrderingComparison.lessThan;9import static org.hamcrest.text.IsEqualIgnoringCase.equalToIgnoringCase;10import static org.junit.Assert.assertThat;11import java.math.BigDecimal;12import org.hamcrest.number.BigDecimalCloseTo;13import org.junit.Test;14public class HamcrestTests {15 // basic hamcrest matchers16 @Test17 public void objectMatcher(){18 // string19 assertThat("João", is(equalTo("João")));20 }21 22 @Test23 public void objectMatcherFail(){24 // string25 assertThat("João", is(equalTo("João")));26 }27 28 @Test29 public void numberMatcher(){30 Integer valor = 10;31 assertThat(valor, allOf(lessThan(12), greaterThan(6)));32 }33 34 @Test35 public void numberMatcher2(){36 BigDecimal _315 = new BigDecimal(315);37 BigDecimal _314 = new BigDecimal(314);38 assertThat(_314, new BigDecimalCloseTo(_315, new BigDecimal(1)));39 }40 41 @Test42 public void textMatcher(){43 assertThat("João Maria", equalToIgnoringCase("joãO mariA"));44 }45 46 @Test47 public void arraymatcher(){48 }49 50 @Test51 public void testAnyOf(){52 String frase = "teste do anyOf";53 assertThat(frase, anyOf(equalToIgnoringCase("blah blah"), containsString("anyOf")));54 }55 56 // Custom hamcrest matchers57 // ...58}...
Source: HamcrestTest.java
1package lectures.unittesting;23import static org.hamcrest.CoreMatchers.anyOf;4import static org.hamcrest.CoreMatchers.anything;5import static org.hamcrest.CoreMatchers.describedAs;6import static org.hamcrest.CoreMatchers.equalTo;7import static org.hamcrest.CoreMatchers.instanceOf;8import static org.hamcrest.CoreMatchers.is;9import static org.hamcrest.CoreMatchers.nullValue;10import static org.hamcrest.CoreMatchers.sameInstance;11import static org.junit.Assert.assertThat;1213import org.hamcrest.Description;14import org.hamcrest.Matcher;15import org.hamcrest.StringDescription;16import org.junit.Test;1718public class HamcrestTest {19 20 // Feels very esoteric and not for typical usage used to override the21 // description22 @Test23 public void describedAsExample() throws Exception {24 Matcher<?> matcher = describedAs("My Description", anything());25 Description description = new StringDescription()26 .appendDescriptionOf(matcher);27 assertThat("My Description", is(description.toString()));28 }29 30 @SuppressWarnings("unchecked")31 @Test32 public void anyOfExampleReturnsTrueIfOneMatches() throws Exception {33 assertThat(34 "Hello",35 is(anyOf(nullValue(), instanceOf(String.class),36 equalTo("Goodbye"))));37 }38 39 @Test40 public void sameInstanceExample() throws Exception {41 Object object = new Object();42 Object sameObject = object;43 assertThat(object, is(sameInstance(sameObject)));44 }4546}
...
Source: RunnerHamcrestTest.java
1package com.tvajjala.runner;2import static org.hamcrest.CoreMatchers.anyOf;3import static org.hamcrest.CoreMatchers.anything;4import static org.hamcrest.CoreMatchers.containsString;5import static org.hamcrest.CoreMatchers.either;6import static org.hamcrest.CoreMatchers.endsWith;7import static org.hamcrest.CoreMatchers.hasItem;8import static org.hamcrest.CoreMatchers.hasItems;9import static org.hamcrest.CoreMatchers.is;10import static org.hamcrest.CoreMatchers.startsWith;11import java.util.Arrays;12import java.util.List;13import org.junit.Assert;14import org.junit.Test;15/**16 *17 * @author ThirupathiReddy V18 *19 */20public class RunnerHamcrestTest {21 @Test22 public void allOfTest() {23 Assert.assertThat("Some", anything());24 }25 @Test26 public void thatTest() {27 Assert.assertThat(99.9, either(is(100.0)).or(is(99.9)));28 Assert.assertThat(99.0, anyOf(is(99.0), is(2929.00)));29 }30 @Test31 public void collectionMatcherTest() {32 final List<Double> list = Arrays.asList(200.0, 222.0, 88.00, 12.59);33 Assert.assertThat(list, hasItem(200.0));34 Assert.assertThat(list, hasItems(12.59, 88.00));35 }36 @Test37 public void stringMatcherTest() {38 Assert.assertThat("Hello world", containsString("world"));39 Assert.assertThat("Hello world", endsWith("world"));40 Assert.assertThat("Hello world", startsWith("Hello"));41 }42}...
...4import static org.hamcrest.CoreMatchers.equalTo;5import static org.hamcrest.CoreMatchers.not;6import static org.hamcrest.CoreMatchers.either;7import static org.hamcrest.CoreMatchers.both;8import static org.hamcrest.CoreMatchers.anyOf;9import static org.hamcrest.CoreMatchers.allOf;10public class AssertThatCompoundValueMatchers {11 @Test12 public void verify_multiple_values() throws Exception {13 double marks = 100.00;14 assertThat(marks, either(equalTo(100.00)).or(equalTo(90.9)));15 assertThat(marks, both(not(99.99)).and(not(60.00)));16 assertThat(marks, anyOf(equalTo(100.00), equalTo(1.00),17 equalTo(55.00), equalTo(88.00), equalTo(67.8)));18 assertThat(marks, not(anyOf(equalTo(0.00), equalTo(200.00))));19 assertThat(marks, not(allOf(equalTo(1.00), equalTo(100.00), equalTo(30.00))));20 }21}...
anyOf
Using AI Code Generation
1import static org.hamcrest.CoreMatchers.anyOf;2import static org.hamcrest.CoreMatchers.containsString;3import static org.hamcrest.CoreMatchers.equalTo;4import static org.hamcrest.CoreMatchers.is;5import static org.hamcrest.CoreMatchers.not;6import static org.hamcrest.CoreMatchers.startsWith;7import static org.junit.Assert.assertThat;8import org.junit.Test;9public class HamcrestMatchersTest {10 public void testAnyOf() {11 String str = "This is a string";12 assertThat(str, anyOf(containsString("is a"), startsWith("This")));13 assertThat(str, anyOf(not(containsString("is a")), startsWith("That")));14 assertThat(str, anyOf(equalTo("This is a string"), equalTo("That is not a string")));15 assertThat(str, anyOf(is("This is a string"), is("That is not a string")));16 }17}18import static org.hamcrest.CoreMatchers.anyOf;19import static org.hamcrest.CoreMatchers.containsString;20import static org.hamcrest.CoreMatchers.equalTo;21import static org.hamcrest.CoreMatchers.is;22import static org.hamcrest.CoreMatchers.not;23import static org.hamcrest.CoreMatchers.startsWith;24import static org.junit.Assert.assertThat;25import org.junit.Test;26public class HamcrestMatchersTest {27 public void testAnyOf() {28 String str = "This is a string";29 assertThat(str, anyOf(containsString("is a"), startsWith("This")));30 assertThat(str, anyOf(not(containsString("is a")), startsWith("That")));31 assertThat(str, anyOf(equalTo("This is a string"), equalTo("That is not a string")));32 assertThat(str, anyOf(is("This is a string"), is("That is not a string")));33 }34}
anyOf
Using AI Code Generation
1import static org.hamcrest.CoreMatchers.anyOf;2import static org.hamcrest.CoreMatchers.containsString;3import static org.hamcrest.CoreMatchers.endsWith;4import static org.hamcrest.CoreMatchers.startsWith;5import static org.hamcrest.MatcherAssert.assertThat;6public class AnyOfExample {7 public static void main(String[] args) {8 assertThat("Hello World", anyOf(startsWith("Hello"), endsWith("World")));9 assertThat("Hello World", anyOf(startsWith("Hello"), endsWith("Universe")));10 assertThat("Hello World", anyOf(containsString("Hello"), containsString("Universe")));11 }12}13Expected: (a string starting with "Hello" or a string ending with "World")14Expected: (a string starting with "Hello" or a string ending with "Universe")15Expected: (a string containing "Hello" or a string containing "Universe")
anyOf
Using AI Code Generation
1import org.hamcrest.CoreMatchers.anyOf2import org.hamcrest.CoreMatchers.is3import org.hamcrest.CoreMatchers.equalTo4import org.hamcrest.MatcherAssert.assertThat5assertThat(1, anyOf(is(2), is(1), is(3)))6assertThat(1, anyOf(equalTo(2), equalTo(1), equalTo(3)))7assertThat(1, anyOf(is(2), is(3)))8assertThat(1, anyOf(equalTo(2), equalTo(3)))9assertThat(1, anyOf(is(1), is(3)))10assertThat(1, anyOf(equalTo(1), equalTo(3)))11assertThat(1, anyOf(is(2), is(1)))12assertThat(1, anyOf(equalTo(2), equalTo(1)))13assertThat(1, anyOf(is(2), is(1), is(3), is(4)))14assertThat(1, anyOf(equalTo(2), equalTo(1), equalTo(3), equalTo(4)))15assertThat(1, anyOf(is(2), is(3), is(4)))16assertThat(1, anyOf(equalTo(2), equalTo(3), equalTo(4)))17assertThat(1, anyOf(is(1), is(3), is(4)))18assertThat(1, anyOf(equalTo(1), equalTo(3), equalTo(4)))19assertThat(1, anyOf(is(2), is(1), is(4)))20assertThat(1, anyOf(equalTo(2), equalTo(1), equalTo(4)))21assertThat(1, anyOf(is(2), is(1), is(3), is(4), is(5)))22assertThat(1, anyOf(equalTo(2), equalTo(1), equalTo(3), equalTo(4), equalTo(5)))23assertThat(1, anyOf(is(2), is(3), is(4), is(5)))24assertThat(1, anyOf(equalTo(2), equalTo(3), equalTo(4), equalTo(5)))25assertThat(1, anyOf(is(1), is(3), is(4), is(5)))26assertThat(1, anyOf(equalTo(1), equalTo(3), equalTo(4), equalTo(5)))27assertThat(1, anyOf(is(2), is(1), is(4), is(5)))28assertThat(1, anyOf(equalTo(2), equalTo
anyOf
Using AI Code Generation
1import org.hamcrest.CoreMatchers;2public class AnyOfExample {3 public void testAnyOf() {4 String fruit = "apple";5 assertThat(fruit, anyOf(equalTo("apple"), equalTo("banana"), equalTo("orange")));6 }7}
How to test a component / bean in Spring Boot
How to disable Spring logging DEBUG messages?
What is the equivalent of TestName rule in JUnit 5?
@Before and @Transactional
How to uninstall Eclipse?
Run unit tests only on Windows
How to handle ordering of @Rule's when they are dependent on each other
Spring profiles and testing
passing Parameterized input using Mockitos
Does reflection breaks the idea of private methods, because private methods can be access outside of the class?
write plain unit tests for components that you can straightly test without loading a Spring container (run them in local and in CI build).
write partial integration tests/slicing unit test for components that you cannot straightly test without loading a Spring container such as components related to JPA, controllers, REST clients, JDBC ... (run them in local and in CI build)
write some full integration tests (end-to-end tests) for some high-level components where it brings values (run them in CI build).
In a general way with Spring any component can be tested in integration tests and only some kinds of components are suitable to be tested unitary(without container).
But note that with or without spring, unitary and integration tests are not opposed but complementary.
You recognize a code to test that doesn't have any dependencies from a Spring container as the component/method doesn't use Spring feature to perform its logical.
Take that FooService
class :
@Service
public class FooService{
private FooRepository fooRepository;
public FooService(FooRepository fooRepository){
this.fooRepository = fooRepository;
}
public long compute(...){
List<Foo> foos = fooRepository.findAll(...);
// core logic
long result =
foos.stream()
.map(Foo::getValue)
.filter(v->...)
.count();
return result;
}
}
FooService
performs some computations and logic that don't need Spring to be executed.
Indeed with or without container the compute()
method contains the core logic we want to assert.
Reversely you will have difficulties to test FooRepository
without Spring as Spring Boot configures for you the datasource, the JPA context, and instrument your FooRepository
interface to provide to it a default implementation and multiple other things.
Same thing for testing a controller (rest or MVC).
How could a controller be bound to an endpoint without Spring? How could the controller parse the HTTP request and generate an HTTP response without Spring? It simply cannot be done.
Using Spring Boot in your application doesn't mean that you need to load the Spring container for any test class you run.
As you write a test that doesn't need any dependencies from the Spring container, you don't have to use/load Spring in the test class.
Instead of using Spring you will instantiate yourself the class to test and if needed use a mock library to isolate the instance under test from its dependencies.
That is the way to follow because it is fast and favors the isolation of the tested component.
Here how to unit-test the FooService
class presented above.
You just need to mock FooRepository
to be able to test the logic of FooService
.
With JUnit 5 and Mockito the test class could look like :
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
@ExtendWith(MockitoExtension.class)
class FooServiceTest{
FooService fooService;
@Mock
FooRepository fooRepository;
@BeforeEach
void init{
fooService = new FooService(fooRepository);
}
@Test
void compute(){
List<Foo> fooData = ...;
Mockito.when(fooRepository.findAll(...))
.thenReturn(fooData);
long actualResult = fooService.compute(...);
long expectedResult = ...;
Assertions.assertEquals(expectedResult, actualResult);
}
}
Writing an end-to-end test requires to load a container with the whole configuration and beans of the application.
To achieve that @SpringBootTest
is the way :
The annotation works by creating the ApplicationContext used in your tests through SpringApplication
You can use it in this way to test it without any mock :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;
@SpringBootTest
public class FooTest {
@Autowired
Foo foo;
@Test
public void doThat(){
FooBar fooBar = foo.doThat(...);
// assertion...
}
}
But you can also mock some beans of the container if it makes sense :
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.boot.test.context.SpringBootTest;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
@SpringBootTest
public class FooTest {
@Autowired
Foo foo;
@MockBean
private Bar barDep;
@Test
public void doThat(){
Mockito.when(barDep.doThis()).thenReturn(...);
FooBar fooBar = foo.doThat(...);
// assertion...
}
}
Note the difference for mocking as you want to mock a plain instance of a Bar
class (org.mockito.Mock
annotation)and that you want to mock a Bar
bean of the Spring context (org.springframework.boot.test.mock.mockito.MockBean
annotation).
Loading a full spring context takes time. So you should be cautious with @SpringBootTest
as this may make unit tests execution to be very long and generally you don't want to strongly slow down the local build on the developer's machine and the test feedback that matters to make the test writing pleasant and efficient for developers.
That's why "slow" tests are generally not executed on the developer's machines.
So you should make them integration tests (IT
suffix instead of Test
suffix in the naming of the test class) and make sure that these are executed only in the continuous integration builds.
But as Spring Boot acts on many things in your application (rest controllers, MVC controllers, JSON serialization/deserialization, persistence, and so for...) you could write many unit tests that are only executed on the CI builds and that is not fine either.
Having end-to-end tests executed only on the CI builds is ok but having also persistence, controllers or JSON tests executed only on the CI builds is not ok at all.
Indeed, the developer build will be fast but as drawback the tests execution in local will detect only a small part of the possible regressions...
To prevent this caveat, Spring Boot provides an intermediary way : partial integration test or the slice testing (as they call it) : the next point.
As explained in the point "Recognizing a test that can be plain tested (without spring))", some components can be tested only with a running container.
But why using @SpringBootTest
that loads all beans and configurations of your application while you would need to load only a few specific configuration classes and beans to test these components?
For example why loading a full Spring JPA context (beans, configurations, in memory database, and so forth) to test the controller part?
And reversely why loading all configurations and beans associated to Spring controllers to test the JPA repository part?
Spring Boot addresses this point with the slice testing feature.
These are not as much as fast than plain unit tests (that is without container) but these are really much faster than loading a whole spring context.
So executing them on the local machine is generally very acceptable.
Each slice testing flavor loads a very restricted set of auto-configuration classes that you can modify if needed according to your requirements.
Some common slice testing features :
To test that object JSON serialization and deserialization is working as expected, you can use the @JsonTest annotation.
To test whether Spring MVC controllers are working as expected, use the
@WebMvcTest
annotation.
To test that Spring WebFlux controllers are working as expected, you can use the
@WebFluxTest
annotation.
You can use the
@DataJpaTest
annotation to test JPA applications.
And you have still many other slice flavors that Spring Boot provides to you.
See the testing part of the documentation to get more details.
Note that if you need to define a specific set of beans to load that the built-in test slice annotations don't address, you can also create your own test slice annotation(https://spring.io/blog/2016/08/30/custom-test-slice-with-spring-boot-1-4).
Some days ago, I have encountered a case where I would test in partial integration a service bean that depends on several beans that themselves also depend on other beans.
My problem was that two deep dependency beans have to be mocked for usual reasons (http requests and a query with large data in database).
Loading all the Spring Boot context looked an overhead, so I tried to load only specific beans.
To achieve that, I annotation the test class with @SpringBootTest
and I specified the classes
attribute to define the configuration/beans classes to load.
After many tries I have gotten something that seemed working but I had to define an important list of beans/configurations to include.
That was really not neat nor maintainable.
So as clearer alternative, I chose to use the lazy bean initialization feature provided by Spring Boot 2.2 :
@SpringBootTest(properties="spring.main.lazy-initialization=true")
public class MyServiceTest { ...}
That has the advantage to load only beans used at runtime.
I don't think at all that using that property has to be the norm in test classes but in some specific test cases, that appears the right way.
Check out the latest blogs from LambdaTest on this topic:
While working on a project for test automation, you’d require all the Selenium dependencies associated with it. Usually these dependencies are downloaded and upgraded manually throughout the project lifecycle, but as the project gets bigger, managing dependencies can be quite challenging. This is why you need build automation tools such as Maven to handle them automatically.
Do you know the test automation market is all set to hit $35 billion by 2026? And when it comes to cross browser testing, JavaScript leads from the front? Javascript is probably the best alternative for Selenium automation, considering its protocol transformation to the W3C standard. In order to make the most of it, the first step is to choose the best test automation frameworks. Among all the JavaScript testing frameworks, two frameworks are most popular- Nightwatch and Protractor.
With the ever-increasing number of languages and frameworks, it’s quite easy to get lost and confused in this huge sea of all these frameworks. Popular languages like C# provide us with a lot of frameworks and it’s quite essential to know which particular framework would be best suited for our needs.
A test automation framework is a set of components that facilitates the execution of tests along with reporting the results of the test execution. However, the discovery of the right test automation framework can be super-challenging since there are so many options at your perusal. Picture this – When performing Selenium using Java, you have to choose from a gruelling list of 10 Java testing frameworks.
Earlier testers would often refrain from using record and replay tools like Selenium IDE for automation testing and opt for using scripting frameworks like Selenium WebDriver, WebDriverIO, Cypress, etc. The major downside of record & playback (or replay) tools is the inability to leverage tools for writing scalable tests.
LambdaTest also has a detailed JUnit tutorial explaining its features, importance, advanced use cases, best practices, and more to help you get started with running your automation testing scripts.
Here are the detailed JUnit testing chapters to help you get started:
You can also check out our JUnit certification if you wish to take your career in Selenium automation testing with JUnit to the next level.
Get 100 minutes of automation test minutes FREE!!