How to set up ServiceBusTrigger with Dependency Injection with .Net Core 6.0 Isolated - azure-servicebus-topics

I currently have a ServiceBus Trigger in .Net Core 6.0 Isolated. Trying to figure out how to Use Dependency Injection, to set up the Trigger. Trying to figure out how to do this with .Net Core 6.0 Isolated.
I have a strongly typed model that is Bound to the appsettings.json file in the Program.cs code. That part works and has been verified. However when trying to do this with .Net Core 6 Isolated It give error about missing reference.
Here's my Config model that is bound to the appsettings.json file. I have left out the appsettings.json file for simplification
public class MyConfig
{
public string Topic { get; set; }
public string SubscriptionName { get; set; }
}
Here is the Service bus trigger class
public class ServiceBusTriggerClass
{
private readonly MyConfig _myConfig;
public ServiceBusTriggerClass(IOptions<MyConfig> config)
{
_myConfig= config.Value;
}
[Function("MySBFunction")]
public async Task MySBFunction([ServiceBusTrigger(_myConfig.Topic, _myConfig.SubscriptionName)] object myObject)
{
// Do things with the myObject thing.
}}

As of 1-13-2022 it is not possible to do this Using .Net 6 Isolated function. The function does not have access to the Host at this point.

Related

Loading AppSettings.json in mock lambda test tool

I have an AWS Lambda Web API and I'm trying to use code that I've used before to load the appsettings.json into memory.
In appsettings.json I have this:
{
"AppSettings": {
"TestValue": "Some value"
}
}
In StartUp.cs I have this:
public class Startup
{
public static IConfiguration Configuration { get; private set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public void ConfigureServices(IServiceCollection services)
{
services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
And in SomeController.cs I have this:
public class SapController : ControllerBase
{
private readonly AppSettings _appSettings;
public SapController(IOptionsMonitor<AppSettings> optionsMonitor)
{
_appSettings = optionsMonitor.CurrentValue;
}
The problem is, under the Mock Lambda Test Tool the _appSettings properties are all null.
I really don't want to load the appsettings using special case code, as seen in this post and described here. I really thought it should load as normal. Am I wrong with this opinion?
Is it really necessary to load appsettings under the mock lambda test tool using this code?:
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.Build();
So, it turns out that for some reason the appsettings is not being passed in to my constructors. So my controller now has this in the constructor:
public MyController(IConfiguration configuration)
{
_appSettings = configuration.GetSection(nameof(AppSettings)).Get<AppSettings>();
}
The short of it appears to be that I need to acquire the AppSettings instance from the Configuration instance, rather than having it passed in via IoC.
I still don't know why, but at least this works.
Try right-clicking your appsettings.Development.json file and set Copy to Output Directory to Copy always. This will ensure that it will be copied to the same directory as your executable upon build, and your app will find and load it.
You can add the file to your .gitignore if you don't want it to be part of your deployment package. Regardless, it will not be read in Production.

How to test method in XUnit that needs UserManager, but uses in-memory database

I'm using ASP.NET Core 3.1 and XUnit for my unit tests.
I built a database context factory class that instantiates an in-memory version of my database:
public static class DbContextFactory
{
public static ApplicationDbContext CreateDbContext()
{
var options = new DbContextOptionsBuilder<ApplicationDbContext>()
.UseInMemoryDatabase(Guid.NewGuid().ToString())
.Options;
var modelBuilder = new ModelBuilder(new ConventionSet());
var dbContext = new ApplicationDbContext(options);
var onModelCreatingMethod = dbContext.GetType().GetMethod("OnModelCreating",
BindingFlags.Instance | BindingFlags.NonPublic);
onModelCreatingMethod.Invoke(dbContext,
new object[] { modelBuilder });
return dbContext;
}
}
This is the current test class I'm trying to use:
public class AdminServiceTests
{
public ApplicationDbContext context { get; set; }
public IAdminService adminService { get; set; }
public AdminServiceTests()
{
this.context = DbContextFactory.CreateDbContext();
this.adminService = new AdminService(userManager, context);
}
[Fact]
public async Task DeleteUserShouldDeleteUser()
{
// What to do ???
}
}
In order for me to test my admin service, I need to provide a user manager. It should be linked with the database I currently have created.
How can I make that happen?
You're making a common mistake of testing the framework. All your test needs to do is ensure that AdminService.DeleteUser calls UserManager.DeleteAsync. Whether or not that spirals down into actually removing the user from the database is 1) not a concern of the service and 2) an implementation detail of both ASP.NET Core Identity and EF Core, both of which have their own extensive test suites to ensure that happens.
As such, you can just use a library like Moq to create a mock of UserManager<TUser> and then do something like:
userManagerMock.Verify(x => x.DeleteAsync(user), Times.Once());
It's worth mentioning here that this also serves to point out a bit of a flaw in this kind of design. You have a dependency on ASP.NET Core Identity whether or not you put an AdminService wrapper around that. Unless your service is doing something special outside of just proxying to UserManager here (e.g. coordinating multiple actions, like maybe deleting the user triggers a notification or something), then your service is pointless, and you should just use UserManager directly. Developers make this kind of mistake constantly; abstraction for the sake of abstraction only hurts your code. It adds additional maintenance concerns, testing concerns, and obscures what the code is actually doing.

How to do Unit Test with Dependency Injection .net Core 2

I start to develop a new web application, I create a Domain Object, Inteface, DAL and BLL...
I would like to test all before use that.
If I use the developed function in web application in .net core 2 I put in Startup.cs some code like this :
public void ConfigureServices(IServiceCollection services)
{
**services.AddTransient<ITableOfTableRepository, DBTableOfTableRepository>();**
services.AddMvc();
services.AddSingleton<IConfiguration>(Configuration);
}
And in my Controller add this code
public class TablesController : Controller
{
private readonly ITableOfTableRepository _repository;
public TablesController(ITableOfTableRepository repository)
{
this._repository = repository;
}
How to do a UnitTest project for testing all before of the use in web application?
How to use dependency Injection in unit test?
BR
If you are trying to develop in a test first approach...
You will pass by several steps:
Your test is not compiling because you need to write a controller action and create an interface
Once you created an interface you could mock/stub it (using framework like NSubstitute or others) and inject when you create the controller
var userService = Substitute.For();
...
var controller = new MyController(userService)
you write the controller code for your test to pass

unable to launch spring-data-rest unit test, RepositoryRestResource not available for #Autowire

I'm porting an app across from JDBC / REST to spring-data-rest and my one and only unit test with fails with the error
NoSuchBeanDefinitionException:
No qualifying bean of type 'com.xxx.repository.ForecastRepository' available
The app was retro-fitted with spring-boot just previously, and now I'm trying to put a new layer in place with spring-data-rest on top of spring-data-jpa.
I'm attempting to work out the correct Java-config according to
Custom Test Slice with Spring Boot 1.4
but I had to deviate from the idiomatic approach because
the #WebMvcTest annotation doesn't suppress the security module which causes the test to fail
the #MockMvcAutoConfiguration fails due to missing dependencies unless I specify #SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK) (see here)
#WebMvcTest and #SpringBootTest are mutually exclusive since they both specify #BootstrapWith and can't run together
So this is the closest I've got but Spring can't locate my #RepositoryRestResource repository:
Repository
#RepositoryRestResource(collectionResourceRel = "forecasts", path = "forecasts")
public interface ForecastRepository extends CrudRepository<ForecastExEncoded,
Long> {
JUnit Test
#RunWith(SpringRunner.class)
#SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = {TestRestConfiguration.class})
public class ForecastRestTests {
#Autowired
private MockMvc mockMvc;
#Autowired
private ForecastRepository forecastRepository;
#Before
public void deleteAllBeforeTests() throws Exception {
forecastRepository.deleteAll();
}
#Test
public void shouldReturnRepositoryIndex() throws Exception {
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(
jsonPath("$._links.forecasts").exists());
}
}
Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
RepositoryRestMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
WebMvcAutoConfiguration.class,
MockMvcAutoConfiguration.class,
MockMvcSecurityAutoConfiguration.class
})
#Import({PropertySpringConfig.class})
public class TestRestConfiguration {}
Also tried...
I tried to configure the unit test with just #WebMvcTest and this #ComponentScan below from How to exclude AutoConfiguration from Spring Boot), in an attempt to simplify it all, however the excludeFilters had no effect.
#ComponentScan(
basePackages="com.xxx",
excludeFilters = {
#ComponentScan.Filter(type = ASSIGNABLE_TYPE,
value = {
SpringBootWebApplication.class,
JpaDataConfiguration.class,
SecurityConfig.class
})
})
I've set Spring's logging to trace because all I can do at this point is try to find clues as to what is happening from log output. So far though without any luck.
I can see in the logging that RepositoryRestConfiguration is loading, but obviously it isn't fed with the right info and I am unable to work out how that is done, after googling and pouring over the Spring docs and API. I think I must have read every relevant question here on SO .
Update 2016-11-16 10:00
One thing I see in the logs which concerns me is this:
Performing dependency injection for test context [DefaultTestContext#2b4a2ec7 [snip...]
classes = '{class com.xxx.TestRestConfiguration,
class com.xxx.TestRestConfiguration}',
i.e. the context lists the configuration class twice. I specified the config class (once only) on the #SpringBootTest#classes annotation. But if I leave off the #classes from the annotation, Spring Boot finds and pulls in all the config via the #SpringBootApplication class.
So is that a hint that I am specifying the configuration in the wrong place? How else would I do it?
After way too much time, I settled on this approach.
Custom Test Slice with Spring Boot 1.4 looked promising but I couldn't get anywhere with it.
While going over and over
Accessing JPA Data with REST
I realised I had to include the JPA setup because spring-data-rest is using them directly - no chance to mock them or run unit tests without an embedded database.
At least not as far as I understand it. Maybe it is possible to mock them and have spring-data-rest run on the mocks against test data, but I think spring-data-rest and spring-data are probably too tightly coupled.
So integration testing it must be.
In the Spring source code provided with the articles above
gs-accessing-data-rest/ApplicationTests.java
the logging shows Spring Boot pulling in the whole configuration for the application context.
So that my SpringBootApplication class is avoided and the security module isn't loaded up, I set up my tests like this:
#RunWith(SpringRunner.class)
#SpringBootTest
#ContextConfiguration(classes = {
JpaDataConfiguration.class,
TestJpaConfiguration.class,
TestRestConfiguration.class,
PropertySpringConfig.class})
public class ForecastRestTests {
#SuppressWarnings("SpringJavaAutowiringInspection")
#Autowired
private MockMvc mockMvc;
#Autowired
private ForecastRepository forecastRepository;
#Before
public void deleteAllBeforeTests() throws Exception {
forecastRepository.deleteAll();
}
#Test
public void shouldReturnRepositoryIndex() throws Exception {
mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk()).andExpect(
jsonPath("$._links.forecasts").exists());
}
}
with these configuration classes:
#Configuration
#EnableJpaRepositories(basePackages = {"com.bp.gis.tardis.repository"})
#EntityScan(basePackages = {"com.bp.gis.tardis.type"})
public class JpaDataConfiguration {
and
#Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
CacheAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class,
TestDatabaseAutoConfiguration.class,
TestEntityManagerAutoConfiguration.class })
public class TestJpaConfiguration {}
and
#Configuration
#OverrideAutoConfiguration(enabled = false)
#ImportAutoConfiguration(value = {
RepositoryRestMvcAutoConfiguration.class,
HttpMessageConvertersAutoConfiguration.class,
WebMvcAutoConfiguration.class,
MockMvcAutoConfiguration.class,
MockMvcSecurityAutoConfiguration.class
})
public class TestRestConfiguration {}
so the TL;DR summary is: use #ContextConfiguration to specify the configuration files that specify #OverrideAutoConfiguration and #ImportAutoConfiguration

Testing web services with JUnit

I'm developing an application to perform a series of tests on various web services. These web services consume and produce json, and for each of them we have a class to model the json request and response. For example:
If the json request for serviceX is something like this:
{
"name":"Alex",
"id":"123"
}
We have a class serviceXrequest like this:
public class serviceXrequest {
String name;
String id;
//Constructor, getters/setters, etc
...
}
With an object of that class as the starting point, we can perform a series of test on the web service. The idea is to make those test as generic as possible so they can be used with any web service by just writing a class that models it's request and a class to model the response.
For that reason, all of the test methods developed so far work with plain java objects. This is an example of what I want to have:
public class WebServiceTest {
String serviceURL;
String requestJson;
String requestClass;
String responseClass;
public WebServiceTest() {}
#Test
public static void Test1() { ... }
#Test
public static void Test2() { ... }
....
#Test
public static void TestN() { ... }
}
And then, from another class, invoke those tests with doing something like this:
public class LoginTest { //To test the login web service, for example
public static void main(String[] args) {
WebServiceTest loginTest = New WebServiceTest();
loginTest.setServiceURL("172.0.0.1/services/login");
loginTest.setRequestJson("{"user":"ale","pass":"1234"}");
...
loginTest.runTests();
}
}
I know it's not that simple, but any ideas on how to get there?
Thanks in advance!!
You might also look into REST-assured
One of the best tools for testing your webservices is SOAP UI, but this is more for functional testing
As well I integrated very well FitNesse tests
JMeter goes hand in hand with LoadUI ..kind of same things in terms of stress and load tests for webservices.
Junit...i never used directly applied to the webservice itself.
Most of the times I had a Spring service called by the implemetation of the WebService interface (Port) and I unit tested that one.
You should consider using http-matchers (https://github.com/valid4j/http-matchers) which let's you write JUnit-tests, using regular hamcrest-matchers (bundled with JUnit) to test your web-service via standard JAX-RS interface.