简体   繁体   中英

Junit test for a method which calls another void method of another component

I have a method A (Check) on which it calls another void method B(wantToSkip). A will throw one exception for which I am going to write junit test. In this case want to avoid calling method B. How can I achieve that? Code is as below:

class A {
    Class c = new Class();
    Public void setC(C c) {
    this.c = c;
}
    String check(){
        try{
            //do something
        } catch(Exception test) {
            c.wantToSkip();
        }
        ...
    }
}

Here I just want to make sure exception test is thrown but want to skip calling method inside it. I tried following but did not work

@Test//(expected= Exception.class)
public void test(){
class c = Mockito.spy(new class());
Mockito.doNothing().when(c).wantToSkip();
check(some arguments);
}

If you provide a setter for Class c, you can use Mockito to achieve what you want to do.

Your unit test would look something like this:

@Mock private Class mockC;

@Test
public void test(){
    A a = new A();
    a.setC(mockC);
    a.check(some arguments);
}

Alternatively you could take your Class c in the constructor, in which case your test could look like this.

@Mock private Class mockC;

@Test
public void test(){
    A a = new A(mockC);
    a.check(some arguments);
}

The mockC has no behaviour specified for when c.wantToSkip() is called, so it won't do anything.

The latest non-beta version for mockito is here: http://mvnrepository.com/artifact/org.mockito/mockito-all/1.10.19

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM