测试方法return具体对象junit
Test method return specific object junit
我正在尝试创建我的第一个测试。
我要证明一个方法 returns 是一个 ContextLambda 类型,我正在使用 assertSame 函数来测试它,但是我的测试失败了,我不知道用什么断言来测试这个,用 assertEquals 也失败了。
我的测试是这样的:
@Test
public void testCanCreateContextForLambda() {
ContextFactory factory = new ContextFactory();
LambdaContext context = factory.forLambda(
new FakeRequest(),
new FakeResponse(),
new FakeLambda()
);
assertSame(LambdaContext.class, context);
}
尝试使用 instanceof
和 assertTrue
:
包括 assertTrue 导入:
import static org.junit.Assert.assertTrue;
然后是实际测试:
@Test
public void testCanCreateContextForLambda() {
ContextFactory factory = new ContextFactory();
LambdaContext context = factory.forLambda(
new FakeRequest(),
new FakeResponse(),
new FakeLambda()
);
assertTrue(context instanceof LambdaContext);
}
只要 context
是 LambdaContext
类型的 class(例如使用接口使其不平凡),这个断言将是微不足道的并且永远是真的。
您对 assertSame
的断言断言 LambdaContext.class == context
。这永远不会是真的。
您可以通过多种方式更正您的断言
context instanceof LambdaContext
将是微不足道的(总是正确的)
context.getClass() == LambdaContext.class
几乎是微不足道的(可能总是正确的)
这些测试可以使用 junit5 库的 assertSame
和 assertTrue
编写(参见其他答案)。
我最好的建议:放弃这个测试并编写一个断言 context
.
的重要属性的测试
我正在尝试创建我的第一个测试。 我要证明一个方法 returns 是一个 ContextLambda 类型,我正在使用 assertSame 函数来测试它,但是我的测试失败了,我不知道用什么断言来测试这个,用 assertEquals 也失败了。 我的测试是这样的:
@Test
public void testCanCreateContextForLambda() {
ContextFactory factory = new ContextFactory();
LambdaContext context = factory.forLambda(
new FakeRequest(),
new FakeResponse(),
new FakeLambda()
);
assertSame(LambdaContext.class, context);
}
尝试使用 instanceof
和 assertTrue
:
包括 assertTrue 导入:
import static org.junit.Assert.assertTrue;
然后是实际测试:
@Test
public void testCanCreateContextForLambda() {
ContextFactory factory = new ContextFactory();
LambdaContext context = factory.forLambda(
new FakeRequest(),
new FakeResponse(),
new FakeLambda()
);
assertTrue(context instanceof LambdaContext);
}
只要 context
是 LambdaContext
类型的 class(例如使用接口使其不平凡),这个断言将是微不足道的并且永远是真的。
您对 assertSame
的断言断言 LambdaContext.class == context
。这永远不会是真的。
您可以通过多种方式更正您的断言
context instanceof LambdaContext
将是微不足道的(总是正确的)context.getClass() == LambdaContext.class
几乎是微不足道的(可能总是正确的)
这些测试可以使用 junit5 库的 assertSame
和 assertTrue
编写(参见其他答案)。
我最好的建议:放弃这个测试并编写一个断言 context
.