断言对象是特定类型 [英] Assert an object is a specific type

查看:87
本文介绍了断言对象是特定类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JUnit中是否可以断言一个对象是一个类的实例?由于各种原因,我在测试中有一个对象,我想检查其类型。它是Object1的类型还是Object2的类型?

Is it possible in JUnit to assert an object is an instance of a class? For various reasons I have an object in my test that I want to check the type of. Is it a type of Object1 or a type of Object2?

目前我有:

assertTrue(myObject instanceof Object1);
assertTrue(myObject instanceof Object2);

这有效,但我想知道是否有更具表现力的方式。

This works but I was wondering if there is a more expressive way of doing this.

例如:

assertObjectIsClass(myObject, Object1);

我可以这样做:

assertEquals(myObject.class, Object1.getClass());

是否有特定的断言方法允许我以更优雅的方式测试对象的类型,流畅的方式?

Is there a specific assert method that allows me to test a type of an object in a more elegant, fluid manner?

推荐答案

你可以使用 assertThat 方法和Matchers JUnit附带。

You can use the assertThat method and the Matchers that comes with JUnit.

看看此链接描述了一些关于JUnit Matchers的内容。

Take a look at this link that describes a little bit about the JUnit Matchers.

示例:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

测试:

import org.junit.Test;

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

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

这篇关于断言对象是特定类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆