TIL_Java Spring the Modern Way_6

-·2021년 3월 1일
0

mokito 어노테이션 적용

@ExtendWith(SpringExtension.class)
class SomeBusinessMockAnnotationsTest {
	@Mock
	DataService dataService;
	@InjectMocks
	SomeBusinessImpl businessImpl;
	@Test
	void findTheGreatestFromAllData() {
		when(dataService.retrieveAllData()).thenReturn(new int[] {24, 15, 3});
		assertEquals(24, businessImpl.findTheGreatestFromAllData());
	}
}

단위테스트를 spring 에 적용

pom.xml

<!-- spring test -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-test</artifactId>
	<scope>test</scope>
</dependency>
<!-- junit -->
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<scope>test</scope>
</dependency>
<!-- mockito -->
<dependency>
	<groupId>org.mockito</groupId>
	<artifactId>mockito-core</artifactId>
	<scope>test</scope>
</dependency>

java context를 이용

@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = SpringIn5StepsBasicApplication.class)
class BinarySearchTest {
	@Autowired
	BinarySearchImpl binarySearch;
	@Test
	void testBasicScenario() {
		int result = binarySearch.binarySearch(new int[] {}, 5);
		assertEquals(3, result);
	}
}

XML context를 이용

@ExtendWith(SpringExtension.class)
@ContextConfiguration(locations = "/testcontext.xml")
class BinarySearchXMLConfiguerationTest {
	@Autowired
	BinarySearchImpl binarySearch;
	@Test
	void testBasicScenario() {
		int result = binarySearch.binarySearch(new int[] {}, 5);
		assertEquals(3, result);
	}
}

src/test/resources/testcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.xsd">

	<import resource="classpath:applicationcontext.xml"/>

</beans>

이렇게 따로 떼서 덮어쓰기 같은거 할수있음

Mokito이용

@ExtendWith(SpringExtension.class)
class SomeCdiBusinessTest {
	
	@InjectMocks
	SomeCdiBusiness someCdiBusiness;
	@Mock
	SomeCdiDao daoMock;
	
	@Test
	void testBasicScenario() {
		Mockito.when(daoMock.getData()).thenReturn(new int[] {2, 4});
		assertEquals(4, someCdiBusiness.findGreatest());
	}
	@Test
	void testBasicScenario_NoElements() {
		Mockito.when(daoMock.getData()).thenReturn(new int[] { });
		assertEquals(Integer.MIN_VALUE, someCdiBusiness.findGreatest());
	}
	@Test
	void testBasicScenario_EqualElements() {
		Mockito.when(daoMock.getData()).thenReturn(new int[] {2,2});
		assertEquals(2, someCdiBusiness.findGreatest());
	}
}

이렇게 context정보를 가져와서 해야될 필요없이 독립적이면서도 여러가지 테스트케이스를 쉽게 만들어서

테스트 해볼수 있음

그래서 가능하면 단위테스트때 스프링의 사용은 피하는게 좋다

profile
거북이는 오늘도 걷는다

0개의 댓글