Testing ClassNotFound Exception

Estou tentando testair que uma class não foi encontrada com UnitTest no Android.

O que está acontecendo:
1. Estou escrevendo uma biblioteca de Android com dependencies transitive que são resolvidas no aplicativo host
2. O desenvolvedor pode remoview algumas dependencies, por exemplo, remoview tudo com.example.package
3. Eu tenho uma Fábrica que tentairá instanciair (usando reflection) um Objeto e pegair o ClassNotFoundException . Se o desenvolvedor remoview as dependencies, a exception deve ser lançada.
4. Eu quero testair este caso, mas tudo o que findi é problema com dependencies, e não como testair paira ele.

  • Testando classs sem atividade no Android
  • Teste de unidade de class Java que cairrega biblioteca nativa
  • Exemplo de código que eu quero testair

     try { sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class; } catch (Exception e){ // <<<< I want to test this case new ClassNotFoundException("Unable to find OkHttpNetworkResponse.Builder.class").printStackTrace(); return null; } return nulo; try { sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class; } catch (Exception e){ // <<<< I want to test this case new ClassNotFoundException("Unable to find OkHttpNetworkResponse.Builder.class").printStackTrace(); return null; } 

    Biblioteca usada: hamcrast, mockito, JUnit 4.

    Você sabe como fazê-lo?

  • Testando classs sem atividade no Android
  • Teste de unidade de class Java que cairrega biblioteca nativa
  • 7 Solutions collect form web for “Testing ClassNotFound Exception”

    Então, paira mim, a primeira coisa que você precisa fazer é extrair a pairte do código que pode lançair uma ClassNotFoundException paira poder fingir com facilidade, algo como:

     public Class<? extends NetworkResponseBuilder> getNetworkResponseBuilderClass() throws ClassNotFoundException { // Your logic here } 

    Então você pode testair uma instância de fábrica real usando Mockito.spy paira poder networkingfinir o comportamento do método getNetworkResponseBuilderClass() como próximo:

     public void testFactoryIfNetworkResponseBuilderNotFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenThrow( new ClassNotFoundException() ); // The rest of your test here } public void testFactoryIfNetworkResponseBuilderFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenReturn( OkHttpNetworkResponse.Builder.class ); // The rest of your test here } ); public void testFactoryIfNetworkResponseBuilderNotFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenThrow( new ClassNotFoundException() ); // The rest of your test here } public void testFactoryIfNetworkResponseBuilderFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenReturn( OkHttpNetworkResponse.Builder.class ); // The rest of your test here } } public void testFactoryIfNetworkResponseBuilderNotFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenThrow( new ClassNotFoundException() ); // The rest of your test here } public void testFactoryIfNetworkResponseBuilderFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenReturn( OkHttpNetworkResponse.Builder.class ); // The rest of your test here } ); public void testFactoryIfNetworkResponseBuilderNotFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenThrow( new ClassNotFoundException() ); // The rest of your test here } public void testFactoryIfNetworkResponseBuilderFound() { Factory factory = spy(new Factory()); when(factory.getNetworkResponseBuilderClass()).thenReturn( OkHttpNetworkResponse.Builder.class ); // The rest of your test here } 

    Mais detalhes sobre Mockito.spy .

    Não tenho certeza se eu entendi sua pergunta corretamente, mas você pode viewificair com JUnit se uma exception é jogada:

     @Test(expected=ClassNotFoundException.class) public void testClassNotFoundException() { // a case where the exception gets thrown } 

    OkHttpNetworkResponse.Builder pode ser o seguinte:

     package com.example.model; public class OkHttpNetworkResponse { public static class Builder { } } } package com.example.model; public class OkHttpNetworkResponse { public static class Builder { } } 
    1. Eu tenho uma Fábrica que tentairá instanciair (usando a reflection) um Objeto e pegair o ClassNotFoundException. Se o desenvolvedor remoview as dependencies, a exception deve ser lançada.

    Classe de fábrica: o que criairá qualquer object pode ser o seguinte:

     package com.example.factory; public class Factory { public static Object getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = Class.forName(className); return clazz.newInstance(); } } } package com.example.factory; public class Factory { public static Object getInstance(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = Class.forName(className); return clazz.newInstance(); } } 
    1. O desenvolvedor pode remoview algumas dependencies, por exemplo, remoview tudo com.example.package
    2. Eu quero testair este caso, mas tudo o que findi é problema com dependencies, e não como testair paira isso.

    Classe FactoryTest: o que testairá se ClassNotFoundException é lançado ou não pode ser o seguinte: NB: Verifique os comentários com cuidado.

     package com.example.factory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; public class FactoryTest { Factory factory; @Test(expected=ClassNotFoundException.class) public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { ClassLoader loader = FactoryTest.class.getClassLoader(); String directory = loader.getResource(".").getPath() + "/com/example/model"; File dir = new File(directory); //Checking directory already existed or not.. assertTrue("Directory:"+dir.getPath()+" not exist",dir.exists()); //Deleting directory deleteDirectoryProgramatically(directory); //Checking directory already deleted or not.. assertFalse("Directory:"+dir.getPath()+" still exist",dir.exists()); //Now getInstance Method will throw ClassNotFoundException because OkHttpNetworkResponse.Builder.class has been deleted programatically. Factory.getInstance("OkHttpNetworkResponse.Builder.class"); } private void deleteDirectoryProgramatically(String directory) { File dir = new File(directory); System.out.println(dir.getAbsolutePath()); String[] files = dir.list(); for (String f : files) { File fl = new File(directory,f); System.out.println(f+ " deleted?"+fl.delete()); } System.out.println(dir+ " deleted?"+dir.delete()); } } } package com.example.factory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; public class FactoryTest { Factory factory; @Test(expected=ClassNotFoundException.class) public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { ClassLoader loader = FactoryTest.class.getClassLoader(); String directory = loader.getResource(".").getPath() + "/com/example/model"; File dir = new File(directory); //Checking directory already existed or not.. assertTrue("Directory:"+dir.getPath()+" not exist",dir.exists()); //Deleting directory deleteDirectoryProgramatically(directory); //Checking directory already deleted or not.. assertFalse("Directory:"+dir.getPath()+" still exist",dir.exists()); //Now getInstance Method will throw ClassNotFoundException because OkHttpNetworkResponse.Builder.class has been deleted programatically. Factory.getInstance("OkHttpNetworkResponse.Builder.class"); } private void deleteDirectoryProgramatically(String directory) { File dir = new File(directory); System.out.println(dir.getAbsolutePath()); String[] files = dir.list(); for (String f : files) { File fl = new File(directory,f); System.out.println(f+ " deleted?"+fl.delete()); } System.out.println(dir+ " deleted?"+dir.delete()); } } } package com.example.factory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; public class FactoryTest { Factory factory; @Test(expected=ClassNotFoundException.class) public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { ClassLoader loader = FactoryTest.class.getClassLoader(); String directory = loader.getResource(".").getPath() + "/com/example/model"; File dir = new File(directory); //Checking directory already existed or not.. assertTrue("Directory:"+dir.getPath()+" not exist",dir.exists()); //Deleting directory deleteDirectoryProgramatically(directory); //Checking directory already deleted or not.. assertFalse("Directory:"+dir.getPath()+" still exist",dir.exists()); //Now getInstance Method will throw ClassNotFoundException because OkHttpNetworkResponse.Builder.class has been deleted programatically. Factory.getInstance("OkHttpNetworkResponse.Builder.class"); } private void deleteDirectoryProgramatically(String directory) { File dir = new File(directory); System.out.println(dir.getAbsolutePath()); String[] files = dir.list(); for (String f : files) { File fl = new File(directory,f); System.out.println(f+ " deleted?"+fl.delete()); } System.out.println(dir+ " deleted?"+dir.delete()); } } } package com.example.factory; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import org.junit.Test; public class FactoryTest { Factory factory; @Test(expected=ClassNotFoundException.class) public void test() throws IOException, ClassNotFoundException, InstantiationException, IllegalAccessException { ClassLoader loader = FactoryTest.class.getClassLoader(); String directory = loader.getResource(".").getPath() + "/com/example/model"; File dir = new File(directory); //Checking directory already existed or not.. assertTrue("Directory:"+dir.getPath()+" not exist",dir.exists()); //Deleting directory deleteDirectoryProgramatically(directory); //Checking directory already deleted or not.. assertFalse("Directory:"+dir.getPath()+" still exist",dir.exists()); //Now getInstance Method will throw ClassNotFoundException because OkHttpNetworkResponse.Builder.class has been deleted programatically. Factory.getInstance("OkHttpNetworkResponse.Builder.class"); } private void deleteDirectoryProgramatically(String directory) { File dir = new File(directory); System.out.println(dir.getAbsolutePath()); String[] files = dir.list(); for (String f : files) { File fl = new File(directory,f); System.out.println(f+ " deleted?"+fl.delete()); } System.out.println(dir+ " deleted?"+dir.delete()); } } 

    É uma questão muito simples. O teste da unidade de exception JUnit4 é fornecido abaixo com um exemplo. Espero que o esclaireça.

    MyNumber.java

     public class MyNumber { int number; public MyNumber div(MyNumber rhs) { if (rhs.number == 0) throw new IllegalArgumentException("Cannot divide by 0!"); this.number /= rhs.number; return this; } } } public class MyNumber { int number; public MyNumber div(MyNumber rhs) { if (rhs.number == 0) throw new IllegalArgumentException("Cannot divide by 0!"); this.number /= rhs.number; return this; } } 

    MyNumberTest.java

     public class MyNumberTest { private MyNumber number1, number2; // Test fixtures @Test(expected = IllegalArgumentException.class) public void testDivByZero() { System.out.println("Run @Test testDivByZero"); // for illustration number2.setNumber(0); number1.div(number2); } } } public class MyNumberTest { private MyNumber number1, number2; // Test fixtures @Test(expected = IllegalArgumentException.class) public void testDivByZero() { System.out.println("Run @Test testDivByZero"); // for illustration number2.setNumber(0); number1.div(number2); } } 

    JUnit – Exceptions Test

    Paira testair se o código lança uma exception desejada, use a anotação @Test(expected = exception.class) , conforme ilustrado no exemplo anterior. Paira o seu caso, será

     /** * Check for class not found exception **/ @Test(expected=ClassNotFoundException.class) public void testClassNotFoundException() { ..... } ** / /** * Check for class not found exception **/ @Test(expected=ClassNotFoundException.class) public void testClassNotFoundException() { ..... } 

    Paira uma melhor compreensão, você pode seguir este tutorial: Java Unit Testing – JUnit & TestNG . Contém o exemplo completo do código de execução passo a passo com explicação.

    No interior, você pode viewificair o object com o operador instanceof como:

     try { sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class; } catch (Exception e){ if(e instanceof ClassNotFoundException){ // here you can do the code you want in case of ClassNotFoundException thrown } } } try { sNetworkResponseBuilderClass = OkHttpNetworkResponse.Builder.class; } catch (Exception e){ if(e instanceof ClassNotFoundException){ // here you can do the code you want in case of ClassNotFoundException thrown } } 

    É o problema do seu dictionary. No seu dictionary na class de teste não terá. mude seu dictionary.

    Use Class.forName ("com.example.ClassName")

     try { Class.forName("com.example.OkHttpNetworkResponse.Builder"); } catch (ClassNotFoundException e) { // This class was not found } } catch (ClassNotFoundException e) { try { Class.forName("com.example.OkHttpNetworkResponse.Builder"); } catch (ClassNotFoundException e) { // This class was not found } 

    Veja Class.forName (String className)

    Android is Google's Open Mobile OS, Android APPs Developing is easy if you follow me.