12

I have:

package com.darlik.test; import org.junit.Assert; public class Test { public static void main(String[] args) { assertTrue(1, 2); } } 

package with org.junit is set and working but in line with assertTrue i have error:

The method assertTrue(int, int) is undefined for the type Test

Why? I use Eclipse.

3
  • assertTrue has the method signature assertTrue(boolean), i.e. assertTrue(actual == expected), see junit.sourceforge.net/javadoc/org/junit/… Commented Aug 17, 2014 at 18:31
  • why use main? Please annotate with test, makes more sense, even in example. Second thing, you don't have appropriate import. Please fix import as suggested by @Reimeus + change what you are comparing inside Commented Aug 17, 2014 at 18:55
  • @MichalGruca Good point - also remember to rename the class since it conflicts with org.junit.Test Commented Aug 17, 2014 at 19:04

5 Answers 5

22

assertTrue is based on a single boolean condition. For example

assertTrue(1 == 2); 

You need to import the statement statically to use

import static org.junit.Assert.assertTrue; 

Typically, however assertEquals is used when comparing 2 parameters, e.g.

public class MyTest { @Test public void testAssert() throws Exception { assertEquals(1, 2); } } 
Sign up to request clarification or add additional context in comments.

Comments

7

From the doc : assertTrue(boolean) or assertTrue(String, boolean) if you want to add a message.

AssertTrue assert that a condition is true, you still have to code such condition for it to be evaluated at runtime.

Comments

7

You have to specify the class that defines that method:

Assert.assertTrue(condition); 

Furthermore you're calling the method with 2 parameters which makes no sense. assertTrue expects a single boolean expression.

Although you can also do this by using a static import:

import static org.junit.Assert.*; 

which will allow you to call it as assertTrue(condition); instead.

Comments

-1

Better try assertThat with matchers. Check this blog about it https://objectpartners.com/2013/09/18/the-benefits-of-using-assertthat-over-other-assert-methods-in-unit-tests/

import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; .... @Test public void testNum() { assertThat(repo.getNum(), is(equalTo(111))); } 

Comments

-1

Delete the module-info.java file if there is any in the project. It's not necessary and is only used if you're using Java's built-in module system.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.