I am new to JUnit . I am working on the ways to get a output like
classname / function name / status / description.
I figured that there is no other way to get success test name other than FrameworkMethod using Rule. Is it possible to set a Rule to a suite which s running with the help of JUnitCore/textui.Thx in advance.!!
Edit:- I tried testwatchman with Junit 4.9b2 but executing suites is not working for me. Any help would be appreciated.
#RunWith(Suite.class)
#SuiteClasses({testclass1.class, testclass2.class})
public class junitCheck {
private static String watchedLog;
#Rule
public MethodRule watchman= new TestWatchman() {
#Override
public void failed(Throwable e, FrameworkMethod method) {
watchedLog+= method.getName() + " " + e.getClass().getSimpleName()
+ "\n";
}
#Override
public void succeeded(FrameworkMethod method) {
watchedLog+= method.getName() + " " + "success!\n";
}
};
}
public class testclass1 {
#Test
public void add()
{
Assert.assertEquals(4,2+3);
}
}
public class testclass2 {
#Test
public void add1()
{
Assert.assertEquals(4,2+2);
}
}
Have a look at the TestWatchman rule.
It won't work with the suite. So the only way is to add an org.junit.rules.TestWatcher to a common super class of the tests.
Related
This question already has answers here:
Interrupt test class at the first test failure
(3 answers)
Closed 1 year ago.
I have to write a test divided into several steps. Each step is based on the previous one so if one fails, testing should be stopped.
#TestMethodOrder(AlphanumericOrder.class)
public class TestCase {
#Test
public void step10() {
Assertions.assertTrue(true);
}
#Test
public void step20() {
Assertions.assertTrue(false);
}
#Test
public void step30() {
Assertions.assertTrue(true);
}
#Test
public void step40() {
Assertions.assertTrue(true);
}
}
In the example above testing should be terminated after step20(). I implemented custom MethodOrder to ensure correct sequence of execution. The problem I have is how to stop other tests after one fails? I tried to implement TestWatcher with no success. Is there any built-in mechanism in JUnit5 that can solve my problem?
Working solution that was shared in the comments:
Reference: Interrupt test class at the first test failure
#ExtendWith(StepwiseExtension.class)
#TestMethodOrder(AlphanumericOrder.class)
public class TestCase {
#Test
public void step10() {
Assertions.assertTrue(true);
}
#Test
public void step20() {
Assertions.assertTrue(false);
}
#Test
public void step30() {
Assertions.assertTrue(true);
}
#Test
public void step40() {
Assertions.assertTrue(true);
}
#BeforeEach
public void before(){
}
}
class StepwiseExtension implements ExecutionCondition, TestExecutionExceptionHandler {
#Override
public ConditionEvaluationResult evaluateExecutionCondition(ExtensionContext extensionContext) {
ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
ExtensionContext.Store store = storeFor(extensionContext, namespace);
String value = store.get(StepwiseExtension.class, String.class);
return value == null ? ConditionEvaluationResult.enabled("No test failures in stepwise tests") :
ConditionEvaluationResult.disabled(String.format("Stepwise test disabled due to previous failure in '%s'", value));
}
#Override
public void handleTestExecutionException(ExtensionContext extensionContext, Throwable throwable) throws Throwable {
ExtensionContext.Namespace namespace = namespaceFor(extensionContext);
ExtensionContext.Store store = storeFor(extensionContext, namespace);
store.put(StepwiseExtension.class, extensionContext.getDisplayName());
throw throwable;
}
private ExtensionContext.Namespace namespaceFor(ExtensionContext extensionContext){
return ExtensionContext.Namespace.create(StepwiseExtension.class, extensionContext.getParent());
}
private ExtensionContext.Store storeFor(ExtensionContext extensionContext, ExtensionContext.Namespace namespace){
return extensionContext.getParent().get().getStore(namespace);
}
}
Please, help me write a JUnit test for this code using Mockito.
class A{
private BlockingQueue<Runnable> jobQueue;
public void methodA(List<String> messages) {
try {
jobQueue.put(() -> methodB(message));
} catch(InterruptedException e) {}
}
private void methodB(Message message) {
//other logic
}
}
Your example lacks context as to what it is methodB is doing... Without knowing what the functionality is that you want to verify, just verifying that methodB gets called wouldn't be a particularly useful test, nor is mocking the BlockingQueue. I'm going to go out on a limb and assume that methodB interacts with another object, and it's this interaction that you really want to verify, if that's the case my code and test would look something like:
class A {
private BlockingQueue<Runnable> jobQueue;
private B b;
public void methodA(Message message) {
try {
jobQueue.put(() -> methodB(message));
} catch (InterruptedException e) {
}
}
private void methodB(Message message) {
b.sendMethod(message);
}
}
class B {
public void sendMethod(Message message) {
// other logic
}
}
And my test would potentially look something like:
class Atest {
private A testSubject;
#Mock
private B b;
#Test
public void testASendsMessage() {
Message message = new Message("HELLO WORLD");
testSubject.methodA(message);
verify(b, timeout(100)).sendMethod(message);
}
#Before
public void setup() throws Exception {
testSubject = new A();
}
}
In general you want to avoid needing to verifying bits with multiple threads in a unit test, save tests with multiple running threads mainly for integration tests but where it is necessary look at Mockito.timeout(), see example above for how to use. Hopefully this helps?
I have a function which should print string.
I want to test through JUnit Is really the function printing what it is supposed to print.
How to do it?
for example, this my function:
public static void test(int a){
System.out.println(a + "^2=" + (a*a));
}
and I want to check that for a = 3 is printing 3^2=9
Ps, I can not change the function.
Why don't you try this.Hope it will work for you.
public void TestPrint {
#Rule
public final StandardOutputStreamLog log = new StandardOutputStreamLog();
#Test
public static void test(int a) {
System.out.print(a + "^2=" + (a*a));
assertEquals("3^2=9", log.getLog());
}
}
I am trying to work with PowerMock, over Mockito; as I loved the API's for whennew() and verifyprivate() but i have some problem when trying to run testsuites with Categories TestRunner in Junit.
For using default JUnit test runners, I created a TestCase and added PowerMockRule as instance field with #Rule annotation. While execution of tests worked like this, ExpectedException TestRule is not working when used in conjunction
Example Code
#PowerMockIgnore ("*")
#PrepareForTest (CustomizedSSHConnection.class)
public class TestExpectedExceptionRule {
private Connection connection;
private ConnectionInfo connectionInfo;
#Rule
public PowerMockRule rule = new PowerMockRule ();
#Rule
public ExpectedException exception = ExpectedException.none ();
#Test
public void testExcepitonWithPowerMockRule() {
exception.expect (NullPointerException.class);
exception.expectMessage ("Image is null");
throw new NullPointerException ("Image is null");
}
}
Instead of using #Rule PowerMockRule if I use #RunWith(PowerMockRunner.class) this testcase will pass.
One other observation is if I annotate PowerMockRule with #ClassRule this succeeds but some of the mocking methods throwing exceptions.
PowerMock creates a deep clone of the TestExpectedExceptionRule object. Because of this it is running the test with a new ExpectedException rule, but you're calling exception.expect (NullPointerException.class) on the original rule. Hence the test fails, because the clone of the ExpectedException rule doesn't expect an exception.
Nevertheless there are at least two solutions for your problem.
RuleChain
Order the rules with JUnit's RuleChain. This needs some additional ugly code, but it works.
private ExpectedException exception = ExpectedException.none ();
private PowerMockRule powerMockRule = new PowerMockRule();
#Rule
public TestRule ruleChain = RuleChain.outerRule(new TestRule() {
#Override
public Statement apply(Statement base, Description description) {
return powerMockRule.apply(base, null, description);
}
}).around(exception);
Fishbowl
If you are using Java 8 then you can replace the ExpectedException rule with the Fishbowl library.
#Test
public void testExcepitonWithPowerMockRule() {
Throwable exception = exceptionThrownBy(
() -> throw new NullPointerException ("Image is null"));
assertEquals(NullPointerException.class, exception.getClass());
assertEquals("Image is null", exception.getMessage());
}
Without Java 8, you have to use an anonymous class.
#Test
public void fooTest() {
Throwable exception = exceptionThrownBy(new Statement() {
public void evaluate() throws Throwable {
throw new NullPointerException ("Image is null");
}
});
assertEquals(NullPointerException.class, exception.getClass());
assertEquals("Image is null", exception.getMessage());
}
I was able to fix this using the expected attribute in the #Test annotation. But the problem with this approach is that am unable to assert the exception message. Which is fine for me for now.
#PowerMockIgnore ("*")
#PrepareForTest (CustomizedSSHConnection.class)
public class TestExpectedExceptionRule {
private Connection connection;
private ConnectionInfo connectionInfo;
#Rule
public PowerMockRule rule = new PowerMockRule ();
#Rule
public ExpectedException exception = ExpectedException.none ();
#Test(expected = NullPointerException.class)
public void testExcepitonWithPowerMockRule() {
throw new NullPointerException ("Image is null");
}
}
I solved this problem by creating a PowerMockTestUtil class that uses a FunctionalInterface.
Utility class:
/**
* Utility class to provide some testing functionality that doesn't play well with Powermock out
* of the box. For example, #Rule doesn't work well with Powermock.
*/
public class PowerMockTestUtil {
public static void expectException(RunnableWithExceptions function, Class expectedClass, String expectedMessage) {
try {
function.run();
fail("Test did not generate expected exception of type " + expectedClass.getSimpleName());
} catch (Exception e) {
assertTrue(e.getClass().isAssignableFrom(expectedClass));
assertEquals(expectedMessage, e.getMessage());
}
}
#FunctionalInterface
public interface RunnableWithExceptions<E extends Exception> {
void run() throws E;
}
}
Sample test:
#Test
public void testValidateMissingQuantityForNewItem() throws Exception {
...
expectException(() -> catalogEntryAssociationImporter.validate(line),
ImportValidationException.class,
"Quantity is required for new associations");
}
I have created two observables.
One of them throws an exception.
obs1 = Observable.from(new Integer[]{1, 2, 3, 4, 5, 6});
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
}
});
Now I invoke them using
Observable.merge(obs2, obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
Now, I dont want my process to halt completely when an exception occurs -
I want to handle it and I want obs1 to continue its work.
I have tried to write it using onErrorResumeNext(), onExceptionResumeNext(), doOnError()
but nothing helped - obs1 did not run.
How can I handle the exception without stopping the other observable from being processed?
Sounds like you need mergeDelayError.
The problem is in your subscriber which is broken. You should catch your exception and call onError. Otherwise, you broke the rx contract.
example :
Observable<Integer> obs1 = Observable.from(Arrays.asList(1, 2, 3, 4, 5, 6));
Observable<Integer> obs2 = Observable.create((Subscriber<? super Integer> subscriber) -> {
subscriber.onError(new NullPointerException());
});
Observable.merge(obs2.onErrorResumeNext((e) -> Observable.empty()), obs1)
.subscribe(new Observer<Integer>() {
#Override public void onCompleted() {
System.out.println("onCompleted");
}
#Override public void onError(Throwable throwable) {
System.out.println("onError");
}
#Override public void onNext(Integer integer) {
System.out.println("onNext - " + integer);
}
});
so if you replace your obs2 code with this, it should work like you expected :
obs2 = Observable.create(new Observable.OnSubscribe<Integer>() {
#Override public void call(Subscriber<? super Integer> subscriber) {
try {
boolean b = getObj().equals(""); // this throws an exception
System.out.println("1");
} catch(Exception ex) {
subscriber.onError(ex);
}
}
});