jUnit의 여러 RunWith 문
단위 테스트를 작성 JUnitParamsRunner
하고 MockitoJUnitRunner
하나의 테스트 클래스 를 사용 하고 싶습니다 .
불행히도 다음은 작동하지 않습니다.
@RunWith(MockitoJUnitRunner.class)
@RunWith(JUnitParamsRunner.class)
public class DatabaseModelTest {
// some tests
}
하나의 테스트 클래스에서 Mockito와 JUnitParams를 모두 사용하는 방법이 있습니까?
사양에 따라 동일한 주석이 달린 요소에 동일한 주석을 두 번 넣을 수 없기 때문에 이렇게 할 수 없습니다.
그렇다면 해결책은 무엇입니까? 해결책은 @RunWith()
당신이 없이는 서있을 수없는 러너와 함께 하나만 놓고 다른 하나를 다른 것으로 교체하는 것입니다. 귀하의 경우에는 제거 MockitoJUnitRunner
하고 프로그래밍 방식으로 수행 할 것이라고 생각합니다 .
실제로 실행되는 유일한 작업은 다음과 같습니다.
MockitoAnnotations.initMocks(test);
테스트 케이스의 시작 부분에서. 따라서 가장 간단한 해결책은이 코드를 setUp()
메서드에 넣는 것입니다.
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
나는 잘 모르겠지만, 아마도 당신은 플래그를 사용하여이 방법의 여러 호출을 피해야한다 :
private boolean mockInitialized = false;
@Before
public void setUp() {
if (!mockInitialized) {
MockitoAnnotations.initMocks(this);
mockInitialized = true;
}
}
그러나 더 나은, 재사용 가능한 솔루션은 JUnt의 규칙으로 구현 될 수 있습니다.
public class MockitoRule extends TestWatcher {
private boolean mockInitialized = false;
@Override
protected void starting(Description d) {
if (!mockInitialized) {
MockitoAnnotations.initMocks(this);
mockInitialized = true;
}
}
}
이제 테스트 클래스에 다음 줄을 추가하십시오.
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
원하는 러너로이 테스트 케이스를 실행할 수 있습니다.
JUnit 4.7 및 Mockito 1.10.17부터이 기능이 내장되어 있습니다. 이 org.mockito.junit.MockitoRule
클래스는. 간단히 가져 와서 라인을 추가 할 수 있습니다.
@Rule public MockitoRule mockitoRule = MockitoJUnit.rule();
시험 수업에.
이 솔루션은이 mockito 예제뿐만 아니라 가능한 모든 러너에게 적용됩니다. 예를 들면 다음과 같습니다. Spring의 경우 러너 클래스를 변경하고 필요한 주석을 추가하기 만하면됩니다.
@RunWith(JUnitParamsRunner.class)
public class DatabaseModelTest {
@Test
public void subRunner() throws Exception {
JUnitCore.runClasses(TestMockitoJUnitRunner.class);
}
@RunWith(MockitoJUnitRunner.class)
public static class TestMockitoJUnitRunner {
}
}
DatabaseModelTest
will be run by JUnit. TestMockitoJUnitRunner
depends on it (by logic) and it will be run inside of the main in a @Test
method, during the call JUnitCore.runClasses(TestMockitoJUnitRunner.class)
. This method ensures the main runner is started correctly before the static class TestMockitoJUnitRunner
sub-runner runs, effectively implementing multiple nested @RunWith
annotations with dependent test classes.
Also on https://bekce.github.io/junit-multiple-runwith-dependent-tests
Since the release of PowerMock 1.6, you can do it as easily as
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(JUnitParamsRunner.class)
public class DatabaseModelTest {
// some tests
}
Explained here https://blog.jayway.com/2014/11/29/using-another-junit-runner-with-powermock/
In my case I was trying to Mock some method in spring bean and
MockitoAnnotations.initMocks(test);
doesn't works. Instead you have to define that bean to constructed using mock method inside your xml file like following.
...
<bean id="classWantedToBeMocked" class="org.mockito.Mockito" factory-method="mock">
<constructor-arg value="com.fullpath.ClassWantedToBeMocked" />
</bean>
...
and add that bean with autowired inside your test class like following.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="file:springconfig.xml")
public class TestClass {
...
@Autowired
private ClassWantedToBeMocked classWantedToBeMocked;
...
when(classWantedToBeMocked.methodWantedToBeMocked()).thenReturn(...);
...
}
check out this link https://bekce.github.io/junit-multiple-runwith-dependent-tests/ using this approach i combined a @RunWith(Parameterized.class) - outer runner - with @RunWith(MockitoJUnitRunner.class) - inner runner. The only tweak i had to add was to make my member variables in the outer class/runner static in order to make them accessible for the inner/nested runner/class. gook luck and enjoy.
I wanted to run SWTBotJunit4ClassRunner and org.junit.runners.Parameterized at the same time, I have parametric tests and I want to screenshots when the SWT test fails (the screenshot feature is provided by the SWTBotJunit4ClassRunner). @bekce's answer is great and first wanted go that route but it was either quirky passing through the arguments. Or doing the parametrized in the subclass and loosing the information what exact tests passed/failed and have only the last screenshot (as the screenshot names get the name from the test itself). So either way it was bit messy.
In my case the SWTBotJunit4ClassRunner is simple enough, so I cloned the source-code of the class, gave it my own name ParametrizedScreenshotRunner and where original was extending the TestRunner, my class is extending the Parameterized class so in essence I can use my own runner instead of the previous two. Boiled down my own runner extends on top of Parameterized runner while implementing the screenshot feature on top of it, now my test use this "hybrid" runner and all the tests work as expected straight away (no need to change anything inside the tests).
This is how it looks like (for sake of brevity I removed all the comments from the listing):
package mySwtTests;
import org.junit.runners.Parameterized;
import org.eclipse.swtbot.swt.finder.junit.ScreenshotCaptureListener;
import org.junit.runner.notification.RunListener;
import org.junit.runner.notification.RunNotifier;
public class ParametrizedScreenshotRunner extends TestRu Parameterized {
public ParametrizedScreenshotRunner(Class<?> klass) throws Throwable {
super(klass);
}
public void run(RunNotifier notifier) {
RunListener failureSpy = new ScreenshotCaptureListener();
notifier.removeListener(failureSpy); // remove existing listeners that could be added by suite or class runners
notifier.addListener(failureSpy);
try {
super.run(notifier);
} finally {
notifier.removeListener(failureSpy);
}
}
}
You can also try this:
@RunWith(JUnitParamsRunner.class)
public class AbstractTestClass {
// some tests
}
@RunWith(MockitoJUnitRunner.class)
public class DatabaseModelTest extends AbstractTestClass {
// some tests
}
참고URL : https://stackoverflow.com/questions/24431427/multiple-runwith-statements-in-junit
'program tip' 카테고리의 다른 글
setInterval () 내에서 clearInterval ()을 호출 할 수 있습니까? (0) | 2020.08.18 |
---|---|
Python3에서 인덱스로 dict_keys 요소에 액세스 (0) | 2020.08.18 |
C ++ 코드에서 UML 생성? (0) | 2020.08.18 |
웹 서버는 몇 개의 소켓 연결을 처리 할 수 있습니까? (0) | 2020.08.18 |
## 및 __LINE __ (위치 매크로와 토큰 연결)로 C 매크로 만들기 (0) | 2020.08.18 |