Используя $(this).css("display", "block")
, вы устанавливаете свойство display
на block
. Если вы хотите проверить значение свойства, вместо этого вам нужно использовать if ($(this).css("display") === "block")
или if ($(this).is(":visible"))
, если вы не смотрите на конкретное значение block
. Более подробную информацию о JQuery.css()
можно найти здесь здесь :
$("#myBtn").click(function(e)
{
e.preventDefault();
var allCategories = document.getElementsByClassName("ProductList");
$(allCategories).each(function()
{
if ($(this).css("display") === "block")
$(this).css("display", "none");
});
});
P1
P2
P3
Однако, ваш Для простоты код можно сократить до следующего, если вы хотите скрыть видимые элементы с помощью класса .ProductList
(при условии, что вы не смотрите на конкретное значение block
для свойства display
):
[ 1128]
$("#myBtn").click(function(e)
{
e.preventDefault();
$(".ProductList:visible").hide();
});
P1
P2
P3
Редактировать после обновления вопроса:
Еще одно решение для вас , может использовать атрибуты data-target
для элементов, где вы регистрируете обработчик click
, например:
Вы можете заключить тестовый код в блок try / catch, перехватить сгенерированное исключение, проверить внутреннюю причину, зарегистрировать / подтвердить / что угодно, а затем повторно выбросить исключение (при желании).
Вы всегда можете сделать это вручную:
@Test
public void someMethod() {
try{
... all your code
} catch (Exception e){
// check your nested clauses
if(e.getCause() instanceof FooException){
// pass
} else {
Assert.fail("unexpected exception");
}
}
Для этой цели я написал небольшое расширение JUnit. Статическая вспомогательная функция принимает тело функции и массив ожидаемых исключений:
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
public class AssertExt {
public static interface Runnable {
void run() throws Exception;
}
public static void assertExpectedExceptionCause( Runnable runnable, @SuppressWarnings("unchecked") Class[] expectedExceptions ) {
boolean thrown = false;
try {
runnable.run();
} catch( Throwable throwable ) {
final Throwable cause = throwable.getCause();
if( null != cause ) {
assertTrue( Arrays.asList( expectedExceptions ).contains( cause.getClass() ) );
thrown = true;
}
}
if( !thrown ) {
fail( "Expected exception not thrown or thrown exception had no cause!" );
}
}
}
Теперь вы можете проверить ожидаемые вложенные исключения следующим образом:
import static AssertExt.assertExpectedExceptionCause;
import org.junit.Test;
public class TestExample {
@Test
public void testExpectedExceptionCauses() {
assertExpectedExceptionCause( new AssertExt.Runnable(){
public void run() throws Exception {
throw new Exception( new NullPointerException() );
}
}, new Class[]{ NullPointerException.class } );
}
}
Это избавит вас от необходимости писать один и тот же код шаблона снова и снова.
Если вы используете последнюю версию JUnit, вы можете расширить средство запуска тестов по умолчанию, чтобы справиться с этой задачей (без необходимости заключать каждый из ваших методов в блок try / catch)
ExtendedTestRunner.java - Новое средство выполнения тестов:
public class ExtendedTestRunner extends BlockJUnit4ClassRunner
{
public ExtendedTestRunner( Class<?> clazz )
throws InitializationError
{
super( clazz );
}
@Override
protected Statement possiblyExpectingExceptions( FrameworkMethod method,
Object test,
Statement next )
{
ExtendedTest annotation = method.getAnnotation( ExtendedTest.class );
return expectsCauseException( annotation ) ?
new ExpectCauseException( next, getExpectedCauseException( annotation ) ) :
super.possiblyExpectingExceptions( method, test, next );
}
@Override
protected List<FrameworkMethod> computeTestMethods()
{
Set<FrameworkMethod> testMethods = new HashSet<FrameworkMethod>( super.computeTestMethods() );
testMethods.addAll( getTestClass().getAnnotatedMethods( ExtendedTest.class ) );
return testMethods;
}
@Override
protected void validateTestMethods( List<Throwable> errors )
{
super.validateTestMethods( errors );
validatePublicVoidNoArgMethods( ExtendedTest.class, false, errors );
}
private Class<? extends Throwable> getExpectedCauseException( ExtendedTest annotation )
{
if (annotation == null || annotation.expectedCause() == ExtendedTest.None.class)
return null;
else
return annotation.expectedCause();
}
private boolean expectsCauseException( ExtendedTest annotation) {
return getExpectedCauseException(annotation) != null;
}
}
ExtendedTest.java - аннотация для пометки методов тестирования:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface ExtendedTest
{
/**
* Default empty exception
*/
static class None extends Throwable {
private static final long serialVersionUID= 1L;
private None() {
}
}
Class<? extends Throwable> expectedCause() default None.class;
}
ExpectCauseException.java - новый оператор JUnit:
public class ExpectCauseException extends Statement
{
private Statement fNext;
private final Class<? extends Throwable> fExpected;
public ExpectCauseException( Statement next, Class<? extends Throwable> expected )
{
fNext= next;
fExpected= expected;
}
@Override
public void evaluate() throws Exception
{
boolean complete = false;
try {
fNext.evaluate();
complete = true;
} catch (Throwable e) {
if ( e.getCause() == null || !fExpected.isAssignableFrom( e.getCause().getClass() ) )
{
String message = "Unexpected exception cause, expected<"
+ fExpected.getName() + "> but was<"
+ ( e.getCause() == null ? "none" : e.getCause().getClass().getName() ) + ">";
throw new Exception(message, e);
}
}
if (complete)
throw new AssertionError( "Expected exception cause: "
+ fExpected.getName());
}
}
Использование:
@RunWith( ExtendedTestRunner.class )
public class MyTests
{
@ExtendedTest( expectedCause = MyException.class )
public void someMethod()
{
throw new RuntimeException( new MyException() );
}
}