简体   繁体   中英

check that method returns instance of corresponding class

I have a simple method that creates new object (in reality it creates rather complex object)

class MyClass {
    public MyObject create() { return new MyObject(); }
}

I want to test that upon create call it returns isntance of MyObject . How to do that using mockito ?

public MyClassTest {
    @Mock
    private MyClass myClassMock;

    @Test
    public void testCreate() {
        ???
    }

There's no need to test that in a statically typed language like Java. If it compiles, it will always create an instance of MyObject , because that's what the return type declares.

If for any reason you do want to check types at runtime (maybe because you want to check stricter criteria than what the type system gives you at that point), there is the instanceof keyword, or Class::isInstance()

Try this:

if (create() instanceof MyObject ) {
   // ...
}

Although there is no real need to test this kind of behavior you could do something like this:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

public MyClassTest {

    @Test
    public void testCreate() {
        MyClass myClass = new MyClass();
        assertThat(myClass.create(), instanceOf(MyObject.class));
    }
}

More information about the used Matcher: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/CoreMatchers.html#instanceOf(java.lang.Class)

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